package com.yantong.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;

import com.yantong.config.LocalRedis;
import com.yantong.constant.*;
import com.yantong.enums.MarketingGroupRulesEnum;
import com.yantong.enums.MarketingGroupTypeEnum;
import com.yantong.enums.PayChannelEnum;
import com.yantong.exception.BDException;
import com.yantong.mapper.*;
import com.yantong.mq.OrderMQProducer;
import com.yantong.pay.yfz.pay.YFZPayutil;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.*;
import com.yantong.quartz.job.OrderNoPyJob;
import com.yantong.quartz.utils.QuartzManager;
import com.yantong.service.*;
import com.yantong.utils.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import static com.yantong.constant.CacheKeyLocal.*;
import static com.yantong.utils.CommonUtils.getSn;

@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderMapper orderMapper;

	@Autowired
	private OrderProductMapper orderProductMapper;

	@Autowired
	private OrderSplitInfoMapper orderSplitInfoMapper;

	@Autowired
	@Lazy
	private MarketingGroupService marketingGroupService;

	@Autowired
	@Lazy
	private TicketService ticketService;

	@Autowired
	private ConfigService configService;


	@Autowired
	private CentreService centreService;

	@Autowired
	private InformationTemplateService informationTemplateService;

	@Autowired
	@Lazy
	private MemberService memberService;

	@Autowired
	private WxNotifyService wxNotifyService;

	@Autowired
	private LocalRedis localRedis;

	@Autowired
	private MemberIntegralService integralService;

	@Autowired
	@Lazy
	private ProductCentreService productCentreService;

	@Autowired
	private ActivityMapper activityMapper;
	@Autowired
	private MemberProductAuthorityMapper memberProductAuthorityMapper;
	@Autowired
	private ActivityProductMapper activityProductMapper;

	@Autowired
	@Lazy
	private MarketingSeckillService marketingSeckillService;

	@Autowired
	private ProductSkuService productSkuService;
	@Autowired
	@Lazy
	private ProductService productService;
	@Autowired
	@Lazy
	private PayService payService;

	@Autowired
	private TicketRecordMapper ticketRecordMapper;
	@Autowired
	private CentreAmountMapper centreAmountMapper;

	@Autowired
	private AmountLogMapper amountLogMapper;
	@Autowired
	private OrderSpecialService orderSpecialService;
	@Autowired
	private MemberIntegralService memberIntegralService;

	@Autowired
	private OrderRefundMapper orderRefundMapper;

	@Autowired
	private JuheOrderMapper juheOrderMapper;

	@Autowired
	private JuheOrderRefundMapper juheOrderRefundMapper;
	@Autowired
	private AddressService addressService;
	@Autowired
	@Lazy
	private ProjectExpService projectExpService;
	@Autowired
	private ProductCentreMapper productCentreMapper;
	@Autowired
	private MemberMapper memberMapper;
	@Autowired
	private DispatchService dispatchService;
	@Autowired
	private CentreTerminalMapper centreTerminalMapper;
	@Autowired
	private CommissionLogMapper commissionLogMapper;
	@Autowired
	private QuartzManager quartzManager;
	@Autowired
	private MemberCartService memberCartService;
	@Autowired
	private InformationGZHTemplateService informationGZHTemplateService;
    @Value("${Applet.TemplatemsgCreateUserUrl}")
    private String templatemsgCreateUserUrl = "";
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private BalanceService balanceService;
    @Autowired
    private UsableTeamMiddleMapper usableTeamMiddleMapper;

    @Autowired
    private WxService wxService;

    @Autowired
    private MyWxpayService myWxpayService;
    @Autowired
    private CentreMapper centreMapper;
    @Autowired
    private CommissionService commissionService;

	private static final Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

	@Override
	public PageUtils<Order> listOrders(ListOrderParams params, int offset, int limit) {
		PageUtils<Order> pageUtils = new PageUtils<>();
		if (params.getStatusFlag() == null) {
			params.setStatusFlag(false);
		}
		int total = orderMapper.countByParams(params);
		if (total > 0) {
			List<Order> list = orderMapper.listByParams(params, new RowBounds(offset, limit));
			for (Order o : list) {
				if (o == null || o.getId() == null) {
					continue;
				}
				o.setRefundFlag(0);

				Long activityId = null;
				List<OrderProduct> orderProducts = null;
				if (params.getDispatchid() != null && params.getDispatchid() == 2) {
					//发起人订单
					Order order = orderMapper.selectByPrimaryKey(o.getSgorderId());
					SpellGroupOrdVo vo = new SpellGroupOrdVo();
					vo.setOrderid(o.getId());
					if (order != null) {
						vo.setPeoplenum(order.getPeoplenum());
					}
					orderProducts = orderProductMapper.getSpellgroupOrdByOrderId(vo);
					if (ValidateUtil.isNotEmptyCollection(orderProducts)) {
						activityId = orderProducts.get(0).getActivityId();
						o.setOrderProducts(orderProducts);
					}
				} else {
					orderProducts = orderProductMapper.getByOrderId(o.getId());
					if (ValidateUtil.isNotEmptyCollection(orderProducts)) {
						o.setOrderProducts(orderProducts);
					}
				}
				//拼团订单
				if (o.getOrderType() == ProductType.Spellgroup.getType()) {
					MarketingGroup marketingGroup = marketingGroupService.getMarketingGroupById(activityId);
					if (null != marketingGroup) {
						o.setMarketingGroup(marketingGroup);
						//拼团总人数
						int marketingGroupNum = getSpellGroupOrdCount(o.getSgorderId());
						o.setPeoplenum(marketingGroupNum);
						//差的人数=拼团人数-已参团人数
						int diffNum = marketingGroup.getNeedJoinGroupNum() - marketingGroupNum;
						orderProducts.get(0).setPeoplenum(diffNum < 0 ? 0 : diffNum);
						orderProducts.get(0).setMarketprice(marketingGroup.getGroupPrice());

						if(OrderStatus.success.getCode() == o.getStatus() ){
							//七天退款期限(支付时间内算起)和优惠券未过期与未核销
							Date endDate = DateUtils.getAddDayDate(o.getPayTime(),7);
							if(new Date().compareTo(endDate) < 0) {
								o.setRefundFlag(1);
								if (marketingGroup.getMarketingGroupType() == 1) {
									//查询该笔订单中是否有优惠券核销
									List<OrderSplitInfo> orderSplitInfoList = orderSplitInfoMapper.selectByOutTradeNo(o.getOutTradeNo());
									orderSplitInfoList.forEach(item -> {
										if(item.getVerifyFlag() != 0){
											o.setRefundFlag(0);
										}
									});
								}
							}
						}
					}
				}
				if(OrderStatus.success.getCode() == o.getStatus() && o.getOrderType() == ProductType.FreeCharge.getType()){
					//七天退款期限(支付时间内算起)和优惠券未过期与未核销
					Date  endDate = DateUtils.getAddDayDate(o.getPayTime(),7);
					if(new Date().compareTo(endDate) < 0){
						//查询该笔订单中是否有优惠券核销
						List<OrderSplitInfo> orderSplitInfoList = orderSplitInfoMapper.selectByOutTradeNo(o.getOutTradeNo());
						o.setRefundFlag(1);
						orderSplitInfoList.forEach(item -> {
							if(item.getVerifyFlag() != 0){
								o.setRefundFlag(0);
							}
						});
					}
				}
			}
			pageUtils.setTotal(total);
			pageUtils.setRows(list);
		}
		return pageUtils;
	}

	@Override
	public List<Order> listOrders(ListOrderParams params) {
		List<Order> list = orderMapper.listByParams(params);
		if (CollectionUtils.isNotEmpty(list)) {
			for (Order o : list) {
				if (o == null || o.getId() == null) {
					continue;
				}
				o.setOrderProducts(orderProductMapper.getByOrderId(o.getId()));
			}
		}
		return list;
	}

	@Override
	public int getSpellGroupOrdCount(Long sgorderId) {
		return orderMapper.getSpellGroupOrdCount(sgorderId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String submitOrderMarketing(MarketingBuyReq req) throws ParseException {

		Member member = memberService.getByKey(req.getMemberId());
		if (member == null) {
			throw new BDException(BusinessCode.MEMBER_INFO_ISNULL);
		}
		String sname = req.getSname();
		String mobile = req.getMobile();
		String iscomment = StringUtils.isEmpty(req.getIscomment()) ? "" : req.getIscomment();

		boolean flag = sname.indexOf("代客下单") == -1;
		if (flag && (StringUtils.isEmpty(member.getMobile()) || StringUtils.isEmpty(member.getRealname()))) {
			//异步更新会员电话
			if (StringUtils.isEmpty(member.getMobile())) {
				member.setMobile(mobile);
			}
			if (StringUtils.isEmpty(member.getRealname())) {
				member.setRealname(sname);
			}
			memberService.updateMemberAsync(member);
		}


		if (StringUtils.isEmpty(sname)) {
			sname = StringUtils.isNotEmpty(member.getRealname()) == true ? member.getRealname() : member.getNickname();
		}

		//电话号码和预约的电话号码都为空的情况下，提示错误信息
		if (StringUtils.isEmpty(mobile) && ValidateUtil.isEmptyString(req.getAppointmentMobile())) {
			if (StringUtils.isNotEmpty(member.getMobile())) {
				mobile = member.getMobile();
			} else {
				throw new BDException(BusinessCode.ORDER_MOBILE_ISNULL);
			}
		}

		List<Map<String, String>> list = new ArrayList<>();
		String orderId = "";
		try {
			if (req.getIsCentreord() == null || req.getIsCentreord() == 0) {
				//校验库存,创建订单,发送消息
				orderId = this.newCheckStockMarketing(member, req.getProducts(), sname, mobile, req.getHouseNo(), list, req.getCouponId(), member.getAddress()
						, req.getAllweight(), req.getDispatchid(), req.getDispatchprice(), iscomment, req.getIsSpellgroup(), req.getOrderId(),
						req.getPromoter(), req.getAppointmentName(), req.getAppointmentMobile(), req.getAppointmentDate(), req.getSeatNum(), req.getCateringType()
						, req.getDispatchtype(), req.getClerkId(), req.getOrderType(), req.getIsSubimtOrgType(), req.getAddressId(), req.getActivityId(),
						req.getGroupRules(), req.getMarketingGroupType(), req.getPortType(), req.getShareMid(), req.getUsableTeamMiddleList());
			}
			if (StringUtils.isEmpty(orderId)) {
				logger.error("创建订单失败平台订单编号为空");
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			//如果抛出异常,把redis回滚
			logger.error("库存集合:{}", list.toString());
			if (CollectionUtils.isNotEmpty(list)) {
				for (Map<String, String> map : list) {
					String cache_key_product_sku_sale = map.get("CACHE_KEY_PRODUCT_SKU_SALE_TOTAL");
					String CACHE_KEY_PRODUCT_SALE = map.get("CACHE_KEY_PRODUCT_SALE_TOTAL");
					String CACHE_KEY_PRODUCT_CENTRE_SKU_SALE = map.get("CACHE_KEY_PRODUCT_CENTRE_SKU_SALE_TOTAL");
					String CACHE_KEY_PRODUCT_CENTRE_SALE = map.get("CACHE_KEY_PRODUCT_CENTRE_SALE_TOTAL");
					if (cache_key_product_sku_sale != null) {
						logger.error("创建订单失败平台sku:{}", map.get("CACHE_KEY_PRODUCT_SKU_SALE"));
						localRedis.increamNum(map.get("CACHE_KEY_PRODUCT_SKU_SALE"), -Integer.valueOf(cache_key_product_sku_sale));
					}
					if (CACHE_KEY_PRODUCT_SALE != null) {
						logger.error("创建订单失败平台:{}", map.get("CACHE_KEY_PRODUCT_SALE"));
						localRedis.increamNum(map.get("CACHE_KEY_PRODUCT_SALE"), -Integer.valueOf(CACHE_KEY_PRODUCT_SALE));
					}
					if (CACHE_KEY_PRODUCT_CENTRE_SKU_SALE != null) {
						logger.error("创建订单失败站点sku:{}", map.get("CACHE_KEY_PRODUCT_CENTRE_SKU_SALE"));
						localRedis.increamNum(map.get("CACHE_KEY_PRODUCT_CENTRE_SKU_SALE"), -Integer.valueOf(CACHE_KEY_PRODUCT_CENTRE_SKU_SALE));
					}
					if (CACHE_KEY_PRODUCT_CENTRE_SALE != null) {
						logger.error("创建订单失败站点:{}", map.get("CACHE_KEY_PRODUCT_CENTRE_SALE"));
						localRedis.increamNum(map.get("CACHE_KEY_PRODUCT_CENTRE_SALE"), -Integer.valueOf(CACHE_KEY_PRODUCT_CENTRE_SALE));
					}
					if (CACHE_KEY_PRODUCT_CENTRE_SALE != null) {
						logger.error("创建订单失败站点:{}", map.get("CACHE_KEY_PRODUCT_CENTRE_SALE"));
						localRedis.increamNum(map.get("CACHE_KEY_PRODUCT_CENTRE_SALE"), -Integer.valueOf(CACHE_KEY_PRODUCT_CENTRE_SALE));
					}

					String GROUP_ACTIVITY_SALES_KEY_CACHE = map.get(RedisKey.GROUP_ACTIVITY_SALES_KEY_CACHE);
					String GROUP_ACTIVITY_SALES_TOTAL_CACHE = map.get(RedisKey.GROUP_ACTIVITY_SALES_TOTAL_CACHE);
					if (ValidateUtil.isNotEmptyString(GROUP_ACTIVITY_SALES_TOTAL_CACHE)) {
						logger.error("创建订单失败sku:{}", GROUP_ACTIVITY_SALES_KEY_CACHE);
						localRedis.increamNum(GROUP_ACTIVITY_SALES_KEY_CACHE, -Integer.valueOf(GROUP_ACTIVITY_SALES_TOTAL_CACHE));
					}
					String GROUP_ACTIVITY_SALES_SKU_KEY_CACHE = map.get(RedisKey.GROUP_ACTIVITY_SALES_SKU_KEY_CACHE);
					String GROUP_ACTIVITY_SALES_SKU_TOTAL_CACHE = map.get(RedisKey.GROUP_ACTIVITY_SALES_SKU_TOTAL_CACHE);
					if (ValidateUtil.isNotEmptyString(GROUP_ACTIVITY_SALES_SKU_TOTAL_CACHE)) {
						logger.error("创建订单失败sku:{}", GROUP_ACTIVITY_SALES_SKU_KEY_CACHE);
						localRedis.increamNum(GROUP_ACTIVITY_SALES_SKU_KEY_CACHE, -Integer.valueOf(GROUP_ACTIVITY_SALES_SKU_TOTAL_CACHE));
					}

					String SECKILL_ACTIVITY_SALES_KEY_CACHE = map.get(RedisKey.SECKILL_ACTIVITY_SALES_KEY_CACHE);
					String SECKILL_ACTIVITY_SALES_TOTAL_CACHE = map.get(RedisKey.SECKILL_ACTIVITY_SALES_TOTAL_CACHE);
					if (ValidateUtil.isNotEmptyString(SECKILL_ACTIVITY_SALES_TOTAL_CACHE)) {
						logger.error("创建订单失败sku:{}", SECKILL_ACTIVITY_SALES_KEY_CACHE);
						localRedis.increamNum(SECKILL_ACTIVITY_SALES_KEY_CACHE, -Integer.valueOf(SECKILL_ACTIVITY_SALES_TOTAL_CACHE));
					}
					String SECKILL_ACTIVITY_SALES_SKU_KEY_CACHE = map.get(RedisKey.SECKILL_ACTIVITY_SALES_SKU_KEY_CACHE);
					String SECKILL_ACTIVITY_SALES_SKU_TOTAL_CACHE = map.get(RedisKey.GROUP_ACTIVITY_SALES_SKU_TOTAL_CACHE);
					if (ValidateUtil.isNotEmptyString(SECKILL_ACTIVITY_SALES_SKU_TOTAL_CACHE)) {
						logger.error("创建订单失败sku:{}", SECKILL_ACTIVITY_SALES_SKU_KEY_CACHE);
						localRedis.increamNum(SECKILL_ACTIVITY_SALES_SKU_KEY_CACHE, -Integer.valueOf(SECKILL_ACTIVITY_SALES_SKU_TOTAL_CACHE));
					}

				}
			}
			if (e instanceof BDException) {
				throw e;
			} else {
				throw new BDException(BusinessCode.CREATE_ORDER_ERROR);
			}

		}
		return orderId;
	}


	/**
	 * 查询用户是否参与过拼团
	 *
	 * @param vo
	 * @return
	 */
	public List<Order> getSpellGroupOrdByMid(SpellGroupOrdVo vo) {
		return orderMapper.getSpellGroupOrdByMid(vo);
	}

	/**
	 * 得到拼团商品订单
	 *
	 * @param vo
	 * @return
	 */
	public List<SpellGroupOrdVo> getSpellGroupOrd(SpellGroupOrdVo vo) {
		return orderMapper.getSpellGroupOrd(vo);
	}


	/**
	 * 得到发起人拼团订单
	 *
	 * @return
	 */
	public List<SpellGroupOrdVo> getSpellGroupOrdById(Long id) {
		return orderMapper.getSpellGroupOrdById(id);
	}


	/**
	 * 得到拼团内订单的用户头像昵称
	 *
	 * @param vo
	 * @return
	 */
	public List<SpellGroupOrdVo> getGroupOrdHead(OrderProductDetailVo vo) {
		return orderMapper.getGroupOrdHead(vo);
	}


	@Override
	public Order getByKey(Long orderId) {
		if (orderId == null) {
			logger.info("orderId is null");
			return null;
		}
		Order order = orderMapper.selectByPrimaryKey(orderId);
		if (order == null) {
			logger.info("not found order by id:{}", orderId);
			return null;
		}
		if (order.getTrId() != null) {
			order.setTicketRecord(ticketService.getRecordByKey(order.getTrId()));
		}
		List<OrderProduct> list = orderProductMapper.getByOrderId(orderId);
		if (CollectionUtils.isNotEmpty(list)) {
			TradeConfig tc = null;
			for (OrderProduct op : list) {
				if (op.getTihuoday() == null) {
					if (tc == null) {
						tc = configService.getTradeConfig(order.getCentreId());
					}
					if (tc != null) {
						op.setTihuoday(tc.getExpectedPickTime());
					}
				}
			}
		}
		order.setOrderProducts(list);
		order.setStatusName(OrderStatus.get(order.getStatus()));
		return order;
	}


	/**
	 * 优惠券即将到期订阅消息
	 * 发送订阅消息
	 */
	@Override
	public void sendTicketOverTime(Long centreId, Long mid, Map<String, String> map) {
		//得到站点
		Centre centre = centreService.getByKey(centreId);
		PlatformConfig platformConfig = configService.getConfigByKey(ConfigKey.TEMPLATE_CONFIG.name(), centre.getCentreId());
		if (platformConfig == null) {
			throw new BDException("站点还未保存基础配置！");
		}
		TemplateConfig templateConfig = JSON.parseObject(platformConfig.getConfigValue(), TemplateConfig.class, Feature.OrderedField);
		InformationTemplate informationTemplate = null;
		if (templateConfig != null) {
			if (ValidateUtil.isNotEmptyString(templateConfig.getTicketOverTimeId())) {
				informationTemplate = informationTemplateService.findDetail(Long.parseLong(templateConfig.getTicketOverTimeId()));
			}
		}
		//得到用户信息
		Member mem = memberService.getTmByKey(mid);
		if (mem == null) {
			throw new BDException("用户信息为空");
		}

		Centre centreParam = new Centre();
		centreParam.setCentreId(mem.getCentreId());
		String accessToken = getCentreAccessToken(centreParam);
		if (StringUtils.isEmpty(accessToken)) {
			throw new BDException("获取accessToken失败");
		}

		Template template = new Template();
		List<TemplateParam> paras = new ArrayList<>();
		//模板id
		if (informationTemplate != null && ValidateUtil.isNotEmptyString(templateConfig.getWxTicketOverTimeId()) && ValidateUtil.isNotEmptyObjectOrString(mem.getAppOpenid())) {
			//模板消息
			HashMap<String, Object> result = JSON.parseObject(informationTemplate.getTemplateValue(), LinkedHashMap.class, Feature.OrderedField);
			HashMap<String, Object> resultEntity = JSON.parseObject(informationTemplate.getTemplateEntity(), LinkedHashMap.class, Feature.OrderedField);
			if (result == null) {
				throw new BDException("订阅模板参数不存在！");
			} else {
				//发送消息参数
				// 1. 通过Map.keySet遍历key和value：
				for (String key : result.keySet()) {
					paras.add(new TemplateParam(result.get(key).toString(), map.get(resultEntity.get(key).toString())));
				}

				template.setTemplateId(templateConfig.getWxTicketOverTimeId());
				template.setTouser(mem.getAppOpenid());
				template.setPage("pages/index/index");

				template.setTemplateParamList(paras);

			}
		}

	}


	/**
	 * 返回asstoken
	 *
	 * @param centre
	 * @return
	 */
	public String getCentreAccessToken(Centre centre) {
		String accessToken = "";
		accessToken = wxService.getAccessToken(centre.getCentreId(), WxTerminal.TERMINAL_GZH.getTerminal());

		return accessToken;
	}

	@Override
	public void sendGZHTicketOverTime(Long centreId, Long mid, Map<String, String> map, String url) {
		Member member = memberService.getByKey(mid);
		if (ValidateUtil.isNotEmptyObjectOrString(member) && ValidateUtil.isNotEmptyString(member.getOpenid()) && ValidateUtil.isNotEmptyObjectOrString(member.getOpenid())) {
			logger.info(map.get("loggerInfo"));

			WxNotifyParam notifyParam = new WxNotifyParam();
			notifyParam.setMessageType(WxMessageType.MESSAGE_TYPE_TEXT.getType());//文本消息

			notifyParam.setCenterId(centreId);
			notifyParam.setGzhOpenId(member.getOpenid());

			notifyParam.setTeminal(WxTerminal.TERMINAL_GZH.getTerminal());

			notifyParam.setContent(map.get("content"));
			wxNotifyService.sendNotify(notifyParam);
		}
	}

	/**
	 * 后台帐号创建成功
	 * 发送订阅消息
	 */
	@Override
	public void sendAccountsTemplateToUser(Long centreId, Long mid, Map<String, String> map) {
		//得到站点
		Centre centre = centreService.getByKey(centreId);
		PlatformConfig platformConfig = configService.getConfigByKey(ConfigKey.TEMPLATE_CONFIG.name(), centre.getCentreId());
		if (platformConfig == null) {
			throw new BDException("站点还未保存基础配置！");
		}
		TemplateConfig templateConfig = JSON.parseObject(platformConfig.getConfigValue(), TemplateConfig.class, Feature.OrderedField);
		InformationTemplate informationTemplate = null;
		if (templateConfig != null) {
			if (ValidateUtil.isNotEmptyString(templateConfig.getTemplateIdCreateUser())) {
				informationTemplate = informationTemplateService.findDetail(Long.parseLong(templateConfig.getTemplateIdCreateUser()));
			}
		}
		//得到用户信息
		Member mem = memberService.getTmByKey(mid);
		if (mem == null) {
			throw new BDException("用户信息为空");
		}

		Centre centreParam = new Centre();
		centreParam.setCentreId(mem.getCentreId());
		centreParam.setRelateAccount("19970728");
		String accessToken = getCentreAccessToken(centreParam);
		if (StringUtils.isEmpty(accessToken)) {
			throw new BDException("获取accessToken失败");
		}

		Template template = new Template();
		List<TemplateParam> paras = new ArrayList<>();
		//模板id
		if (informationTemplate != null && ValidateUtil.isNotEmptyString(templateConfig.getWxTemplateIdCreateUser()) && ValidateUtil.isNotEmptyObjectOrString(mem.getAppOpenid())) {
			//模板消息
			HashMap<String, Object> result = JSON.parseObject(informationTemplate.getTemplateValue(), LinkedHashMap.class, Feature.OrderedField);
			HashMap<String, Object> resultEntity = JSON.parseObject(informationTemplate.getTemplateEntity(), LinkedHashMap.class, Feature.OrderedField);
			if (result == null) {
				throw new BDException("订阅模板参数不存在！");
			} else {
				//发送消息参数
				// 1. 通过Map.keySet遍历key和value：
				for (String key : result.keySet()) {
					paras.add(new TemplateParam(result.get(key).toString(), map.get(resultEntity.get(key).toString())));
				}

				template.setTemplateId(templateConfig.getWxTemplateIdCreateUser());
				template.setTouser(mem.getAppOpenid());
				template.setPage("pages/index/index");

				template.setTemplateParamList(paras);

			}
		}

	}

	@Override
	public Integer countByOrder(Order order) {
		if (order.getMid() == null) {
			return 0;
		}
		OrderExample orderExample = new OrderExample();
		OrderExample.Criteria criteria = orderExample.createCriteria();
		criteria.andMidEqualTo(order.getMid());
		return orderMapper.countByExample(orderExample);
	}

	/**
	 * 条件查询订单商品列表
	 *
	 * @param params
	 * @param
	 * @return
	 */
	@Override
	public PageUtils<OrderProductDetailVo> ordProductlistByParams(OrderProductDetailVo params, int offset, int limit) {
		PageUtils<OrderProductDetailVo> pageUtils = new PageUtils<>();
		if (params.getTmid().equals("0")) {
			params.setTmid(null);
		}
		int total = orderMapper.ordProcountByParams(params);
		if (total > 0) {
			List<OrderProductDetailVo> list = orderMapper.ordProductlistByParams(params, new RowBounds(offset, limit));
			pageUtils.setTotal(total);
			pageUtils.setRows(list);
		}
		return pageUtils;
	}

	/**
	 * 得到平台商品的总成本，总利益
	 *
	 * @param params
	 * @return
	 */
	@Override
	public OrderProductDetailVo getBaseProductMoneyTotal(OrderProductDetailVo params) {
		return orderMapper.getBaseProductMoneyTotal(params);
	}

	/**
	 * 条件查询平台订单商品列表
	 *
	 * @param params
	 * @param
	 * @return
	 */
	@Override
	public PageUtils<OrderProductDetailVo> ordProductBaselistByParams(OrderProductDetailVo params, int offset, int limit) {
		PageUtils<OrderProductDetailVo> pageUtils = new PageUtils<>();
		int total = orderMapper.ordProcountbaseByParams(params);
		if (total > 0) {
			List<OrderProductDetailVo> list = orderMapper.ordProductBaselistByParams(params, new RowBounds(offset, limit));
			pageUtils.setTotal(total);
			pageUtils.setRows(list);
		}
		return pageUtils;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int closeOrder(Long orderId, String closeIp, String desc) {
		if (orderId == null) {
			logger.info("closeOrder failed, lose orderId !");
			return 0;
		}
		localRedis.increamNum(CLOSED_ORDER.concat(orderId.toString()), 1);
		Order order = orderMapper.selectByPrimaryKey(orderId);
		if (order == null) {
			logger.info("not found order by id：{}", orderId);
			return 0;
		}
		if (order.getPayIntegral().compareTo(BigDecimal.ZERO) > 0) {
			//退还积分
			integralService.obtainIntegral(order.getMid(), order.getPayIntegral().doubleValue(), orderId, order.getOrdersn());
		}
		if (OrderStatus.wait_pay.getCode() == order.getStatus()) {
			if (order.getTrId() != null) {
				//退还优惠券
				ticketService.updateRecordToNoUse(order.getTrId());
			}
		}
		order.setCloseTime(new Date());
		order.setRemark(desc);
		order.setStatus(OrderStatus.cancel.getCode());
		List<OrderProduct> list = orderProductMapper.getByOrderId(orderId);
		int r = orderMapper.updateByPrimaryKeySelective(order);
		this.closeOrderProduct(orderId);
		if (r > 0) {
			this.refundProductsStock(list, order.getOrderType());
		}
		return r;
	}


	/**
	 * 扣减库存
	 *
	 * @param list
	 * @return
	 */
	private int refundProductsStock(List<OrderProduct> list, Integer orderType) {
		if (CollectionUtils.isEmpty(list)) {
			return 0;
		}
		for (OrderProduct op : list) {
			if (op.getStatus() > OrderStatus.wait_send.getCode()) {
				logger.info("product:{},current status is not wait send", op.getShortTitle());
				continue;
			}
			Long centreProductId = op.getProductId();
			Long centreSkuId = op.getSkuId();
			ProductCentre pc = new ProductCentre();
			if (orderType != ProductType.FreeCharge.getType()) {
				pc = productCentreService.getByKeyWithCache(centreProductId);
				if (pc == null) {
					continue;
				}
			}
			Long productId = pc.getProductId();
			Integer total = op.getTotal();
			if (productId == null || productId == 0) {
				//拼团商品
				if (orderType == ProductType.Spellgroup.getType()) {
					Long activityId = op.getActivityId();
					Long skuId = op.getSkuId();
					String activitySaleKey = String.format(RedisKey.GROUP_ACTIVITY_SALES_TOTAL_CACHE, activityId);
					//扣除商品的销量
					localRedis.increamNum(activitySaleKey, -total);
					//修改拼团商品的库存
					int r = marketingGroupService.changeStock(total, activityId);
					if (r < 1) {
						localRedis.increamNum(activitySaleKey, total);
						throw new BDException(BusinessCode.REFUND_PRODUCT_STOCK_ERROR);
					}
					MarketingGroup marketingGroup = marketingGroupService.getMarketingGroupById(activityId);
					//多规格商品
					if(MarketingGroupTypeEnum.ORDINARY.getCode().equals(marketingGroup.getMarketingGroupType())){
						if (pc.getHasoption() == 1) {
							String activitySkuSaleKey = String.format(RedisKey.GROUP_ACTIVITY_SALES_SKU_TOTAL_CACHE, activityId, skuId);
							//扣除商品的销量
							localRedis.increamNum(activitySkuSaleKey, -total);
							//修改拼团商品的库存
							int rSku = marketingGroupService.changeSkuStockAlone(total, activityId, skuId);
							if (rSku < 1) {
								localRedis.increamNum(activitySkuSaleKey, total);
								throw new BDException(BusinessCode.REFUND_PRODUCT_STOCK_ERROR);
							}
						}
					}
				} else if (orderType == ProductType.FreeCharge.getType()) {
					//大礼包库存
					Long activityId = op.getProductId();
					String activitySaleKey = String.format(RedisKey.GIFT_PACKS_ACTIVITY_SALES_TOTAL_CACHE, activityId);
					//扣除商品的销量
					localRedis.increamNum(activitySaleKey, -total);
					//修改拼团商品的库存
					int r = activityMapper.changeStock(total, activityId);
					if (r < 1) {
						localRedis.increamNum(activitySaleKey, total);
						throw new BDException(BusinessCode.REFUND_PRODUCT_STOCK_ERROR);
					}
				} else {
					//商户自卖商品
					if (centreSkuId == null || centreSkuId == 0) {
						//不带SKU
						logger.info("refund centre product not have sku!");
					} else {
						//带SKU
						ProductSkuCentre psc = productCentreService.getSkuByKeyWithCache(centreSkuId);
						if (psc != null) {
							localRedis.increamNum(CACHE_KEY_PRODUCT_CENTRE_SKU_SALE.concat(String.valueOf(centreSkuId)), -total);
							int r = productCentreService.refundSkuStock(total, psc);
							if (r < 1) {
								localRedis.increamNum(CACHE_KEY_PRODUCT_CENTRE_SKU_SALE.concat(String.valueOf(centreSkuId)), total);
								throw new BDException(BusinessCode.REFUND_PRODUCT_STOCK_ERROR);
							}
						}
					}
					localRedis.increamNum(CACHE_KEY_PRODUCT_CENTRE_SALE.concat(String.valueOf(centreProductId)), -total);
					int r = productCentreService.refundStock(total, pc);
					if (r < 1) {
						localRedis.increamNum(CACHE_KEY_PRODUCT_CENTRE_SALE.concat(String.valueOf(centreProductId)), total);
						throw new BDException(BusinessCode.REFUND_PRODUCT_STOCK_ERROR);
					}
				}
			} else {

				//平台商品
				Product product = productService.getByKeyWithCache(productId);
				if (product == null) {
					continue;
				}
				if (centreSkuId == null || centreSkuId == 0) {
					//无SKU
					logger.info("refund platform product not have sku!");
				} else {
					//带SKU
					ProductSkuCentre psc = productCentreService.getSkuByKeyWithCache(centreSkuId);
					if (psc != null) {
						Long skuId = psc.getSkuId();
						if (skuId != null && skuId > 0) {
							ProductSku ps = productSkuService.getSkuByKeyWithCache(skuId);
							if (ps != null) {
								localRedis.increamNum(CACHE_KEY_PRODUCT_SKU_SALE.concat(String.valueOf(skuId)), -total);
								int r = productSkuService.refundStock(total, ps);
								if (r < 1) {
									localRedis.increamNum(CACHE_KEY_PRODUCT_SKU_SALE.concat(String.valueOf(skuId)), total);
									throw new BDException(BusinessCode.REFUND_PRODUCT_STOCK_ERROR);
								}
							}
						}
					}
				}
				localRedis.increamNum(CACHE_KEY_PRODUCT_SALE.concat(String.valueOf(productId)), -total);
				int r = productService.refundStock(total, product);
				if (r < 1) {
					localRedis.increamNum(CACHE_KEY_PRODUCT_SALE.concat(String.valueOf(productId)), total);
					throw new BDException(BusinessCode.REFUND_PRODUCT_STOCK_ERROR);
				}

			}
		}
//        redisLock.unlock(RLockKey.REFUND_STOCK_LOCK_KEY);
		return 1;
	}

	@Override
	public int closeOrderProduct(Long orderId) {
		if (orderId == null) {
			return 0;
		}
		OrderProduct op = new OrderProduct();
		op.setStatus(OrderStatus.cancel.getCode());
		op.setCancelTime(new Date());

		OrderProductExample ope = new OrderProductExample();
		ope.or().andOrderidEqualTo(orderId);
		return orderProductMapper.updateByExampleSelective(op, ope);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int sendGoods(Long orderId) {
		if (orderId == null) {
			return 0;
		}
		Order order1 = orderMapper.selectByPrimaryKey(orderId);
		/*   if (order1.getCentreId()==21){*/
		//团购订单
		if (order1.getSgorderId() != null && order1.getPromoter() != null) {
			//拼团未成功 不容许发货
			if (order1.getSpellgroupStu() != 2) {
				throw new BDException("拼团未成功不允许发货");
			}
		}
		Order order = new Order();
		order.setId(orderId);
		order.setStatus(OrderStatus.wait_received.getCode());
		order.setSendTime(new Date());
		OrderProduct op = new OrderProduct();
		op.setOrderid(orderId);
		op.setStatus(OrderStatus.wait_received.getCode());
		OrderProductExample orderProductExample = new OrderProductExample();
		OrderProductExample.Criteria criteria = orderProductExample.createCriteria();
		criteria.andOrderidEqualTo(orderId);
		criteria.andStatusEqualTo(OrderStatus.wait_send.getCode());
		orderProductMapper.updateByExampleSelective(op, orderProductExample);
		return orderMapper.updateByPrimaryKeySelective(order);
     /*   }else {
            return 0;
        }*/
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int confirmReceived(Long orderId) {
		if (orderId == null) {
			return 0;
		}
		Order order = orderMapper.selectByPrimaryKey(orderId);
		if (order == null || (order.getStatus() != OrderStatus.wait_received.getCode()
				//堂食和自提订单，在待取餐情况下直接取餐也是调用此接口
				&& order.getStatus() != OrderStatus.merchant_finish_order.getCode()
				//外卖配送订单 在配送中 配送完成调用此接口
				&& order.getStatus() != OrderStatus.goods_sending.getCode())) {
			return 0;
		}
		order.setId(orderId);
		order.setStatus(OrderStatus.delivery_success.getCode());
		order.setFetchTime(new Date());

		OrderProductExample orderProductExample = new OrderProductExample();
		OrderProductExample.Criteria criteria = orderProductExample.createCriteria();
		criteria.andOrderidEqualTo(orderId)
				.andStatusEqualTo(OrderStatus.wait_received.getCode());
		List<OrderProduct> ops = orderProductMapper.selectByExample(orderProductExample);
		if (CollectionUtils.isNotEmpty(ops)) {
			for (OrderProduct op : ops) {
				op.setStatus(OrderStatus.delivery_success.getCode());
				orderProductMapper.updateByPrimaryKeySelective(op);
				centreService.saveAmountLog(orderId, order.getCentreId(), op, op.getOrdersn());

			}
			//查询该笔订单使用过的站点优惠券的总金额
			String ticketAmt = ticketRecordMapper.sumTicketByOrderId(orderId);
			if (!org.springframework.util.StringUtils.isEmpty(ticketAmt) && !ticketAmt.equals("0")) {
				CentreAmount centreAmount = centreAmountMapper.getByKey(order.getCentreId());
				//结算下一笔订单
				AmountLog al = new AmountLog();
				al.setOrderId(orderId);
				al.setCentreId(order.getCentreId());
				al.setOrderSn(order.getOrdersn());
				al.setMoney(new BigDecimal("-" + ticketAmt));//扣减
				al.setFlowType(11);//站点结算扣除优惠券金额
				al.setRemark("订单平台结算给站点扣除优惠券金额：" + ticketAmt + " 订单号:" + order.getOrdersn() + "【变动金额" + centreAmount.getAmount() + "->" + centreAmount.getAmount().subtract(new BigDecimal(ticketAmt)) + "】");
				al.setBeforeamount(centreAmount.getAmount());
				al.setAfteramount(centreAmount.getAmount().subtract(new BigDecimal(ticketAmt)));

				amountLogMapper.saveAmountLog(al);
				centreAmountMapper.deductAmount(order.getCentreId(), new BigDecimal(ticketAmt));

			}
		}

		//订单确认收货特殊逻辑处理
		OrderSpecialDTO orderSpecialDTO = new OrderSpecialDTO();
		orderSpecialDTO.setOrder(order);
		orderSpecialService.orderBusinessProcess(orderSpecialDTO);

		//拼团订单一二级推荐人分佣
		if (order.getOrderType() == ProductType.Spellgroup.getType()) {
			payService.marketingGroupCommission(order);
			order.setStatus(OrderStatus.success.getCode());
		}

		List<OrderProduct> orderProductList = orderProductMapper.getByOrderId(orderId);
		//赠送积分
		if (orderProductList != null) {
			for (OrderProduct orderProduct : orderProductList) {
				if (orderProduct.getCredit() != null) {
					memberIntegralService.addMemberIntegral(order.getMid(), new BigDecimal(orderProduct.getCredit()), order.getId(), "购买" + orderProduct.getProductName() + "赠送");

				}
			}
		}

		return orderMapper.updateByPrimaryKeySelective(order);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int refundOrder(Long orderId, Long aid, String aname) {
		if (orderId == null) {
			return 0;
		}
		Order order = orderMapper.selectByPrimaryKey(orderId);
		if (OrderStatus.wait_refund.getCode() == order.getStatus()) {
			throw new BDException(BusinessCode.ORDER_REFUNDED_ERROR);
		}
		OrderProduct op = new OrderProduct();
		op.setOrderid(orderId);
		op.setStatus(OrderStatus.wait_refund.getCode());
		//修改订单商品待退款
		orderProductMapper.updateByParam(op);//

		OrderRefund orderRefund = new OrderRefund();
		orderRefund.setOid(order.getId());
		orderRefund.setOldstatus(order.getStatus());
		orderRefund.setrMid(order.getMid());
		orderRefund.setPayopenid(order.getPayopenid());
		orderRefund.setAid(aid);
		orderRefund.setAname(aname);
		orderRefund.setStatus(RefundStatus.wait_check.getCode());
		orderRefund.setOrderprice(order.getOrderprice());
		orderRefund.setPayprice(order.getPayprice());
		orderRefund.setDeductcredit2(order.getDeductcredit2());
		//  BigDecimal orderPrice=BigDecimal.valueOf(orderProductMapper.getNormalPriceByOrderId(orderId));

		Double applyPrice = Double.parseDouble("0");
		//取消订单数
		int cancelNum = orderProductMapper.countCancelByOrderId(order.getId());
		if (order.getTrId() != null && cancelNum > 0) {
			//比例
			BigDecimal proportion = new BigDecimal("0");
			//未扣优惠卷价格
			String countMoney = orderProductMapper.sumOrdProductById(order.getId());
			//得到比例四舍五入保留4位小数
			proportion = (order.getPayprice().divide(new BigDecimal(countMoney), 4, BigDecimal.ROUND_HALF_UP)).setScale(4, BigDecimal.ROUND_HALF_UP);
			//单品取消总金额
			Double price = Double.parseDouble("0");
			//得到单品取消的订单商品Id数据集合
			List<OrderProduct> productIds = orderProductMapper.getOrderProdctId(order.getId());
			if (productIds.size() > 0) {
				for (OrderProduct ordProduct : productIds) {
					OrderProduct orderProduct = orderProductMapper.selectByPrimaryKey(ordProduct.getId());
					//最终比例价格 商品总价乘以汇率保留四位小数四舍五入
					price = price + ((orderProduct.getPrice().multiply(proportion)).setScale(4, BigDecimal.ROUND_HALF_UP)).doubleValue();
				}
			}
			//退款金額為支付金額減掉之前單品取消的金額四舍五入
			applyPrice = order.getPayprice().subtract(new BigDecimal(price)).doubleValue();
		} else {
			//用了优惠卷没有单品取消的
			if (order.getPayprice() != null && order.getTrId() != null) {
				applyPrice = order.getPayprice().doubleValue();
			} else {
				//没用优惠卷
				applyPrice = orderProductMapper.getNormalPriceByOrderId(orderId);
			}
		}
		//积分 退款金额比例
		if (cancelNum > 0 && order.getDeductcredit() > 0 && order.getDeductprice().doubleValue() > 0 && order.getTrId() == null) {
			BigDecimal proportion = new BigDecimal("0");
			String countMoney = orderProductMapper.sumOrdProductById(order.getId());
			proportion = (order.getPayprice().divide(new BigDecimal(countMoney), 4, BigDecimal.ROUND_HALF_UP)).setScale(4, BigDecimal.ROUND_HALF_UP);
			Double price = Double.parseDouble("0");
			List<OrderProduct> productIds = orderProductMapper.getOrderProdctId(order.getId());
			if (productIds.size() > 0) {
				for (OrderProduct ordProduct : productIds) {
					OrderProduct orderProduct = orderProductMapper.selectByPrimaryKey(ordProduct.getId());
					price = price + ((orderProduct.getPrice().multiply(proportion)).setScale(4, BigDecimal.ROUND_HALF_UP)).doubleValue();
				}
			}
			applyPrice = order.getPayprice().subtract(new BigDecimal(price)).doubleValue();
		} else if (order.getTrId() == null && cancelNum == 0 && order.getDeductprice().doubleValue() > 0) {
			applyPrice = order.getPayprice().doubleValue();
		}
		orderRefund.setApplyprice(new BigDecimal(applyPrice));
		orderRefund.setRefundtype(order.getPaytype());
		orderRefund.setRefundsn(getSn("SR"));
		orderRefundMapper.insertSelective(orderRefund);

		order.setStatus(OrderStatus.wait_refund.getCode());
		return orderMapper.updateByPrimaryKeySelective(order);
	}



	@Override
	public int update(Order order) {
		return orderMapper.updateByPrimaryKeySelective(order);
	}

	/**
	 * 条件查询平台订单商品列表导出没有分页
	 *
	 * @param params
	 * @return
	 */
	@Override
	public List<OrderProductDetailVo> ordProductBaselistByParamsExp(OrderProductDetailVo params) {
		return orderMapper.ordProductBaselistByParamsExp(params);
	}


	@Override
	public PageUtils<JuheOrder> juheOrdersList(Long mid, Long teamId, Long centerId, String ordersn, Integer paystatus, Integer payType, Date startTime, Date endTime, int offset, int limit) {
		PageUtils<JuheOrder> pageUtils = new PageUtils<>();
		//查询门店下面所有工单订单数据
		Map<String, Object> params = new HashMap<>();
		if (StringUtils.isNotEmpty(ordersn)) {
			params.put("ordersn", ordersn);
		}
		if (centerId != null) {
			params.put("centerId", centerId);
		}
		if (teamId != null) {
			params.put("teamId", teamId);
		}
		if (mid != null) {
			params.put("mid", mid);
		}
		if (paystatus != null) {
			params.put("paystatus", paystatus);
		}
		if (startTime != null) {
			params.put("start", startTime);
		}
		if (endTime != null) {
			params.put("end", endTime);
		}
		if (payType != null) {
			params.put("payType", payType);
		}
		int total = juheOrderMapper.totalByParams(params);
		if (total > 0) {
			//查询快递直发订单商品
			List<JuheOrder> list = juheOrderMapper.listByParams(params, new RowBounds(offset, limit));
			for (JuheOrder juheOrder : list) {
				if (juheOrder.getTrId() != null) {
					TicketRecord ticketRecord = ticketRecordMapper.getByKey(juheOrder.getTrId());
					if (ticketRecord != null) {
						juheOrder.setTicketName(ticketRecord.getTicketName());
						juheOrder.setTicketId(ticketRecord.getTicketId());
					}
					Date payTime = juheOrder.getPayTime();
					payTime = DateUtils.getAddDayDate(payTime, 7);
					if (new Date().compareTo(payTime) <= 0) {
						juheOrder.setRefundFlag(true);
					} else {
						juheOrder.setRefundFlag(false);
					}
				}
				juheOrder.setJuheOrderRefund(juheOrderRefundMapper.selectByRefundNo(juheOrder.getRefundNo()));
			}
			pageUtils.setTotal(total);
			pageUtils.setRows(list);
		}
		return pageUtils;
	}


	/**
	 * 根据订单id得到商品订单list
	 *
	 * @param orderid
	 * @return
	 */
	@Override
	public List<OrderProduct> getOrderProductListByOrdId(Long orderid) {
		return orderProductMapper.getByOrderId(orderid);
	}

	@Override
	public int completeOrder(Order order) {
		if (order == null) {
			return 0;
		}
		order.setFinishTime(new Date());
		order.setStatus(OrderStatus.success.getCode());
		return orderMapper.updateByPrimaryKeySelective(order);
	}

	@Override
	public Map<String, Object> shopCount(ShopCountParams shopCountParams, int offset, int limit) {
		if (shopCountParams.getMid() == null) {
			return null;
		}
		Map<String, Object> result = new HashMap<>(4);
		int startH = 20, startM = 30, endH = 20, endM = 0;
		TradeConfig config = configService.getTradeConfig(shopCountParams.getCentreId());
		if (config != null) {
			startH = config.getNodeHour() == null ? startH : config.getNodeHour();
			startM = config.getNodeMin() == null ? startM : config.getNodeMin();
			endH = config.getFreeEndHour() == null ? endH : config.getFreeEndHour();
			endM = config.getFreeEndMin() == null ? endM : config.getFreeEndMin();
		}

		Integer timeType = shopCountParams.getTimeType();
		Date start = shopCountParams.getStart();
		Date end = shopCountParams.getEnd();
		if (TimeType.TODAY.getCode().equals(timeType)) {
			start = DateUtils.getAppointTime(DateUtils.getAddDayDate(new Date(), -1), startH, startM);
			end = DateUtils.getAppointTime(new Date(), endH, endM);
		} else if (TimeType.YESTERDAY.getCode().equals(timeType)) {
			start = DateUtils.getAppointTime(DateUtils.getAddDayDate(new Date(), -2), startH, startM);
			end = DateUtils.getAppointTime(DateUtils.getAddDayDate(new Date(), -1), endH, endM);
		} else {
			start = DateUtils.getAppointTime(DateUtils.getAddDayDate(start, -1), startH, startM);
			end = DateUtils.getAppointTime(end, endH, endM);
		}

		shopCountParams.setStart(start);
		shopCountParams.setEnd(end);
		PageUtils<Map<String, Object>> pageUtils = new PageUtils<>();
		if (shopCountParams.getType() == 0) {
			/**按商品统计**/
			int total = orderProductMapper.countSalesGroupByProduct(shopCountParams);
			if (total > 0) {
				pageUtils.setTotal(total);
				List<Map<String, Object>> list = orderProductMapper.getSalesGroupByProduct(shopCountParams, new RowBounds(offset, limit));
				//门店才需要看明细数据，供应商只需总数
				for (Map<String, Object> item : list) {
					Long productId = (Long) item.get("productId");
					shopCountParams.setProductId(productId);
					if (shopCountParams.getSupplyId() != null) {
						item.put("teamNum", orderProductMapper.countCommonderBuyNum(shopCountParams));
					}
					if (shopCountParams.getMid() != null) {
						item.put("detail", orderProductMapper.getSalesGroupByMid(shopCountParams));
					}
				}
				pageUtils.setRows(list);
			}
		} else {
			/**按会员统计**/
			int total = orderProductMapper.countSalesGroupByMid(shopCountParams);
			if (total > 0) {
				pageUtils.setTotal(total);
				List<Map<String, Object>> list = orderProductMapper.getSalesGroupByMid(shopCountParams, new RowBounds(offset, limit));
				if (shopCountParams.getMid() != null) {
					for (Map<String, Object> item : list) {
						Long mid = (Long) item.get("mid");
						shopCountParams.setMemberId(mid);
						item.put("detail", orderProductMapper.getSalesGroupByProduct(shopCountParams));
					}
				}
				pageUtils.setRows(list);
			}
		}
		result.put("countList", pageUtils);
		result.put("salesTotal", orderProductMapper.getSaleTotal(shopCountParams));
		return result;
	}


	/**
	 * 订单详情
	 *
	 * @param orderId
	 * @return
	 */
	@Override
	public Order getByKeyAndProductId(Long orderId, Long id) {
		if (orderId == null) {
			logger.info("orderId is null");
			return null;
		}
		Order order = orderMapper.selectByPrimaryKey(orderId);
		if (order == null) {
			logger.info("not found order by id:{}", orderId);
			return null;
		}
		if (order.getTrId() != null) {
			order.setTicketRecord(ticketService.getRecordByKey(order.getTrId()));
		}
		List<OrderProduct> list = orderProductMapper.getByOrderId(orderId);
		//筛选快递直发订单
		list = list.stream().filter(OrderProduct -> OrderProduct.getId().intValue()
				== id).collect(Collectors.toList());
		if (CollectionUtils.isNotEmpty(list)) {
			TradeConfig tc = null;
			for (OrderProduct op : list) {
				if (op.getTihuoday() == null) {
					if (tc == null) {
						tc = configService.getTradeConfig(order.getCentreId());
					}
					if (tc != null) {
						op.setTihuoday(tc.getExpectedPickTime());
					}
				}
			}
		}
		order.setOrderProducts(list);
		order.setStatusName(OrderStatus.get(order.getStatus()));
		return order;
	}


	@Override
	public Order getByPayNo(String payNo) {
		Order order = orderMapper.getByPayNoSumPrice(payNo);
		if (order == null) {
			logger.info("not found order by id:{}", payNo);
			return null;
		}

		return order;
	}



	/**
	 * 售后订单条件查询订单列表
	 *
	 * @param params
	 * @return
	 */
	@Override
	public PageUtils<WorkListVo> workOrderlistByParams(ListOrderParams params, int offset, int limit) {
		PageUtils<WorkListVo> pageUtils = new PageUtils<>();
		//查询门店下面所有工单订单数据
		List<WorkListVo> list = orderMapper.workOrderlistByParams(params, new RowBounds(offset, limit));
		if (list.size() <= 0) {
			return pageUtils;
		}
		int total = orderMapper.countWorkOrderByParams(params);
		if (total <= 0) {
			return pageUtils;
		}

		//0-全部工单 1-发起售后列表 5-售后中列表 6-售后已完成列表
		int status = params.getStatus().intValue();
		for (WorkListVo o : list) {
			if (o == null || o.getId() == null) {
				continue;
			}
			if (status == 5 || status == 6) {
				//替换合计
				o.setOrderprice(o.getMoney());
				//替换订单编号
				o.setOrdersn(o.getWorksn());
			}
			List<OrderProduct> produtList = null;
			if (status == 1) {
				produtList = orderProductMapper.getByOrderId(o.getId());
			} else {
				produtList = orderProductMapper.getByProdutId(o.getOgid());
			}
			List<WorkProductVo> workProductVoList = new ArrayList<>();
			for (OrderProduct model : produtList) {
//				Integer opStatus = model.getStatus();
				//订单有退款过
				if (o.getWrkStu() != null) {
					if (status == 1) {
						//不处理
						model.setTotal(model.getTotal() - model.getRefundNum());
					} else if (o.getWrkStu() == WorkOrderStatus.over.getCode()) {
						model.setStatus(OrderStatus.success.getCode());
						model.setTotal(o.getNums());
					} else if (o.getWrkStu() == WorkOrderStatus.untreated.getCode() || o.getWrkStu() == WorkOrderStatus.financeDeal.getCode()) {
						model.setStatus(OrderStatus.work_access.getCode());
						model.setTotal(o.getNums());
					}
				}
				if (model.getTotal() == 0) {
					continue;
				}
				WorkProductVo vo = new WorkProductVo();
				BeanUtils.copyProperties(model, vo);
				workProductVoList.add(vo);
			}
			o.setOrderProducts(workProductVoList);
		}
		pageUtils.setTotal(total);
		pageUtils.setRows(list);
		return pageUtils;
	}


	//计算版本支付金额以及有效期
	@Override
	public BuyProjectVo calcProjectExpCharge(Member member, Integer serviceDays, ProjectExp projectExp) {
		BuyProjectVo buyProjectVo = new BuyProjectVo();
		BigDecimal payPrice = BigDecimal.ZERO;
		Date expiredDate = null;
		BigDecimal removePrice = BigDecimal.ZERO;
		Integer isupgrade = 0;
		Integer isTrialVersion = 0;
		BigDecimal refReward = BigDecimal.ZERO;
		BigDecimal agentReward = BigDecimal.ZERO;
		if (null == serviceDays) {//未传值的，默认为1
			serviceDays = 1;
		}

		//查询商户信息（过期时间），商户信息不存在的则按第一次购买版本处理
		Centre centre = centreService.getBymid(member.getId());

		ProjectExp oldProject = null;
		//商户存在，并且，已经支付成功，则表示已经购买过
		if (centre != null) {
			oldProject = projectExpService.getByKey(centre.getProjectexpId());
		}

		if (oldProject != null) {//已购买过版本的
			buyProjectVo.setFirstBuy(centre.getPayStatus() != CenterPayStatus.PAIED.getStatus());
			if (projectExp.getChargeType().equals(1)) {
				if (oldProject.getId().equals(projectExp.getId())) {//未更换版本（续费）
					//判断商户有效期
					if (centre.getExpiredDate() != null && centre.getExpiredDate().after(new Date())) {
						//商户在有效期范围内 购买的天数在商户有效期的基础上增加
						expiredDate = DateUtils.getAddDayDate(centre.getExpiredDate(), serviceDays);
						payPrice = projectExp.getPrice().multiply(new BigDecimal(serviceDays));
					} else {
						expiredDate = DateUtils.getAddDayDate(new Date(), serviceDays);
						payPrice = projectExp.getPrice().multiply(new BigDecimal(serviceDays));
					}
				} else {//更换版本
					if (oldProject.getChargeType().equals(0)) {//试用版
						//试用版更换收费版需要支付开户费
						expiredDate = DateUtils.getAddDayDate(new Date(), serviceDays);
						payPrice = projectExp.getPrice().multiply(new BigDecimal(serviceDays));
						removePrice = projectExp.getRemovePrice();
						refReward = projectExp.getRefReward();
						agentReward = projectExp.getAgentReward();
						isupgrade = 1;
					} else {
						//暂时以全额缴纳费用,从当天开始，不考虑在有效期的减扣逻辑
						expiredDate = DateUtils.getAddDayDate(new Date(), serviceDays);
						payPrice = projectExp.getPrice().multiply(new BigDecimal(serviceDays));
					}
				}
			} else if (projectExp.getChargeType().equals(2)) {//按年收费
				if (oldProject.getId().equals(projectExp.getId())) {//未更换版本（续费）
					//判断商户有效期
					if (centre.getExpiredDate() != null && centre.getExpiredDate().after(new Date())) {
						//商户在有效期范围内 购买的天数在商户有效期的基础上增加
						expiredDate = DateUtils.getAddYearDate(centre.getExpiredDate(), serviceDays);
						payPrice = projectExp.getPrice().multiply(new BigDecimal(serviceDays));
					} else {
						expiredDate = DateUtils.getAddYearDate(new Date(), serviceDays);
						payPrice = projectExp.getPrice().multiply(new BigDecimal(serviceDays));
					}
				} else {//更换版本
					if (oldProject.getChargeType().equals(0)) {//试用版
						//试用版更换收费版需要支付开户费
						expiredDate = DateUtils.getAddYearDate(new Date(), serviceDays);
						payPrice = projectExp.getPrice().multiply(new BigDecimal(serviceDays));
						removePrice = projectExp.getRemovePrice();
						refReward = projectExp.getRefReward();
						agentReward = projectExp.getAgentReward();
						isupgrade = 1;
					} else {
						//暂时以全额缴纳费用,从当天开始，不考虑在有效期的减扣逻辑
						expiredDate = DateUtils.getAddYearDate(new Date(), serviceDays);
						payPrice = projectExp.getPrice().multiply(new BigDecimal(serviceDays));
					}

				}
			} else if (projectExp.getChargeType().equals(0)) {
				//试用版本续费
				throw new BDException("试用版无法续费使用！");
			}
		} else {//未购买过版本的
			buyProjectVo.setFirstBuy(true);
			if (projectExp.getChargeType().equals(CenterChargeType.DAY.getType())) {//按天收费
				expiredDate = DateUtils.getAddDayDate(new Date(), serviceDays);
				payPrice = projectExp.getPrice().multiply(new BigDecimal(serviceDays));
				removePrice = projectExp.getRemovePrice();
				refReward = projectExp.getRefReward();
				agentReward = projectExp.getAgentReward();
				isupgrade = 1;
			} else if (projectExp.getChargeType().equals(CenterChargeType.YEAR.getType())) {//按年收费
				expiredDate = DateUtils.getAddYearDate(new Date(), serviceDays);
				payPrice = projectExp.getPrice().multiply(new BigDecimal(serviceDays));
				removePrice = projectExp.getRemovePrice();
				refReward = projectExp.getRefReward();
				agentReward = projectExp.getAgentReward();
				isupgrade = 1;
			} else if (projectExp.getChargeType().equals(CenterChargeType.TRIAL.getType())) {//试用
				expiredDate = DateUtils.getAddDayDate(new Date(), 7);//7天
				payPrice = BigDecimal.ZERO;
				isTrialVersion = 1;
			}
		}
		buyProjectVo.setExpiredDate(expiredDate);
		buyProjectVo.setPayPrice(payPrice);
		buyProjectVo.setRemovePrice(removePrice);
		buyProjectVo.setIsupgrade(isupgrade);
		buyProjectVo.setIsTrialVersion(isTrialVersion);
		buyProjectVo.setRefReward(refReward);
		buyProjectVo.setAgentReward(agentReward);
		buyProjectVo.setChargeType(projectExp.getChargeType());
		return buyProjectVo;
	}

	/**
	 * 计算优惠券实际优惠金额
	 *
	 * @param trId
	 * @param orderPrice
	 * @return
	 */
	@Override
	public BigDecimal calcTicketAmount(Long trId, BigDecimal orderPrice, Long centreId, List<ProductCentre> list, Integer
			cateringType, Map<String, String> skuMap, BigDecimal postage) {
		if (trId == null) {
			return BigDecimal.ZERO;
		}
		Map map = new HashMap<>();
		map.put("ticketId", trId);
		map.put("centreId", centreId);
		TicketRecord tr = ticketRecordMapper.getTicketRecordsByParam(map);
		if (tr == null) {
			return BigDecimal.ZERO;
		}
		ticketService.giftPacksAfterSale(tr);
		Ticket ticket = ticketService.getByKey(tr.getTicketId());
		BigDecimal amount = tr.getAmount();
		Integer type = tr.getType();
		if (amount == null || type == null) {
			throw new BDException(BusinessCode.TICKET_RECORD_ERROR);
		}
		if (TicketType.SINGLE_COUPON.getCode() == type) {
			return this.deductionTicke(amount, ticket, list, cateringType, skuMap);
		} else if (TicketType.VOUCHER.getCode() == type) {
			return this.deductionTicke(amount, ticket, list, cateringType, skuMap);
		} else if (!(TicketType.PINKAGE.getCode() == type)) {
			return amount.multiply(orderPrice).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP);
		} else if (TicketType.PINKAGE.getCode() == type) {
			if (postage.compareTo(new BigDecimal(Integer.parseInt(ticket.getCondition().toString()))) > -1) {
				postage = postage.subtract(ticket.getAmount());
				if (postage.compareTo(BigDecimal.ZERO) == -1) {
					return postage;
				}
				return ticket.getAmount();
			}
			return new BigDecimal(0);
		} else {
			//免邮卷在该方法无法处理,返回一个负数等待后续;
			return new BigDecimal(-1);
		}

	}

	/**
	 * 指定商品或指定分类的抵扣优惠券处理
	 */
	private BigDecimal deductionTicke(BigDecimal amount, Ticket ticket, List<ProductCentre> list, Integer cateringType, Map<String, String> skuMap) {

		BigDecimal amountReturn = BigDecimal.ZERO;
		//单品抵扣券
		if (TicketRange.RANGE_PRODUCT.getCode().equals(ticket.getRangeType()) && ValidateUtil.isNotEmptyString(ticket.getProductId())) {
			//指定的商品id分割
			String[] productIdArray = ticket.getProductId().split(",");

			//指定商品
			for (ProductCentre productCentre : list) {
				ProductSkuCentre productSkuCentre = null;
				if (productCentre.getHasoption() != null && productCentre.getHasoption() == 1) {
					if (productCentre.getId() != null && ValidateUtil.isNotEmptyString(skuMap.get(productCentre.getId().toString()))) {
						productSkuCentre = productCentreService.getSkuBySpecs(skuMap.get(productCentre.getId().toString()));
					}
					if (productSkuCentre == null) {
						throw new BDException(BusinessCode.ORDER_PRODUCT_SKU_ERROR);
					}
				}
				for (int i = 0; i < productIdArray.length; i++) {
					if (productCentre.getId().toString().equals(productIdArray[i])) {
						BigDecimal price = BigDecimal.ZERO;
						{
							if (productSkuCentre != null) {
								price = productSkuCentre.getMarketprice();
							} else {
								price = productCentre.getMarketprice();
							}
						}

						if (price.compareTo(amountReturn) > 0) {
							amountReturn = price;
						}
					}
				}
			}
		} else if (TicketRange.RANGE_CATEGORY.getCode().equals(ticket.getRangeType())
				&& ticket.getPcate() != null) {
			//指定分类
			List<ProductCentre> collect;
			if (ticket.getCcate() != null) {
				collect = list.stream().filter(productCentre -> productCentre.getCcate() != null && productCentre.getCcate().equals(ticket.getCcate())).collect(Collectors.toList());
			} else {
				collect = list.stream().filter(productCentre -> productCentre.getCcate() != null && productCentre.getPcate().equals(ticket.getPcate())).collect(Collectors.toList());
			}

			//分类下取价钱最高的
			if (ValidateUtil.isNotEmptyCollection(collect)) {
				for (ProductCentre productCentre : collect) {
					BigDecimal price = BigDecimal.ZERO;
					ProductSkuCentre productSkuCentre = null;
					if (productCentre.getHasoption() != null && productCentre.getHasoption() == 1) {
						if (productCentre.getId() != null && ValidateUtil.isNotEmptyString(skuMap.get(productCentre.getId().toString()))) {
							productSkuCentre = productCentreService.getSkuBySpecs(skuMap.get(productCentre.getId().toString()));
						}
						if (productSkuCentre == null) {
							throw new BDException(BusinessCode.ORDER_PRODUCT_SKU_ERROR);
						}
					}
					 {
						if (productSkuCentre != null) {
							price = productSkuCentre.getMarketprice();
						} else {
							price = productCentre.getMarketprice();
						}

					}

					if (price.compareTo(amountReturn) > 0) {
						amountReturn = price;
					}
				}
			}
		} else {
			if (TicketType.VOUCHER.getCode() == ticket.getType()) {
				amountReturn = amount;
			}
		}
		//抵扣券业务处理
		if (TicketType.VOUCHER.getCode() == ticket.getType()) {
			if (amount.compareTo(amountReturn) < 0) {
				amountReturn = amount;
			}
		}
		return amountReturn;
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public String submitOrder1(OrderReq req) throws ParseException {
		Member member = memberService.getByKey(req.getMemberId());
		if (member == null) {
			throw new BDException(BusinessCode.MEMBER_INFO_ISNULL);
		}
		String sname = StringUtils.isNotEmpty(req.getSname()) ? req.getSname() : member.getNickname();
		String mobile = req.getMobile();
		if (StringUtils.isEmpty(mobile)) {
			mobile = member.getMobile();
		}
		String iscomment = StringUtils.isEmpty(req.getIscomment()) ? "" : req.getIscomment();
		Address address = null;
		if (req.getAddressId() != null) {
			address = addressService.getByKey(req.getAddressId());
		}
		boolean flag = sname.indexOf("代客下单") == -1;
		if (flag && (StringUtils.isEmpty(member.getMobile()) || StringUtils.isEmpty(member.getRealname()))) {
			//异步更新会员电话
			if (StringUtils.isEmpty(member.getMobile())) {
				member.setMobile(mobile);
			}
			if (StringUtils.isEmpty(member.getRealname())) {
				member.setRealname(sname);
			}
			memberService.updateMemberAsync(member);
		}


		if (StringUtils.isEmpty(sname)) {
			sname = StringUtils.isNotEmpty(member.getRealname()) == true ? member.getRealname() : member.getNickname();
		}

		//电话号码和预约的电话号码都为空的情况下，提示错误信息
		if (StringUtils.isEmpty(mobile) && ValidateUtil.isEmptyString(req.getAppointmentMobile())) {
			if (StringUtils.isNotEmpty(member.getMobile())) {
				mobile = member.getMobile();
			} else if (address != null) {
				mobile = address.getMobile();
			} else {
				throw new BDException(BusinessCode.ORDER_MOBILE_ISNULL);
			}
		}

		List<Map<String, String>> list = new ArrayList<>();
		String orderId = "";
		try {
			if ((req.getIsCentreord() == null || req.getIsCentreord() == 0) && (req.getIsCentreUpgrade() == null || req.getIsCentreUpgrade() == 0)
					&& (req.getIsStores() == null || req.getIsStores() == 0)) {
				logger.info("---进入普通订单---");
				if (req.getOrderType() == null) {
					req.setOrderType(0);
				}
				//校验库存,创建订单,发送消息
				orderId = this.newCheckStock(member, req.getProducts(), sname, mobile, req.getHouseNo(), list, req.getCouponId(), member.getAddress()
						, req.getAllweight(), req.getDispatchid(), req.getDispatchprice(), iscomment, req.getIsSpellgroup(), req.getOrderId(),
						req.getPromoter(), req.getAppointmentName(), req.getAppointmentMobile(), req.getAppointmentDate(), req.getSeatNum(), req.getCateringType()
						, req.getDispatchtype(), req.getClerkId(), req.getOrderType(), req.getAddressId(), req.getTeamId(), req.getGroupRules(), req.getPortType(), req.getShareMid(), req.getShareOpenId());

				logger.info("---结束普通订单---");
			} else if (req.getIsCentreord() != null && req.getIsCentreord() == 1) {
				//站点支付订单
				orderId = this.newCheckStock2(member, sname, mobile, req.getHouseNo(), req.getProjectExpId(),
						member.getAddress(), iscomment, req.getReferrals(), req.getIsupgrade(), req.getClerkId(), req.getServiceDays());
			} else if (req.getIsCentreUpgrade() != null && req.getIsCentreUpgrade() == 1) {
				//站点升级超级店主支付订单
				orderId = this.newCheckStock3(member, sname, mobile, req.getHouseNo(), member.getAddress(), iscomment,
						req.getReferrals(), req.getClerkId());
			} else if (req.getIsStores() != null && req.getIsStores() == 1) {
				orderId = this.newCheckStock4(member, sname, mobile, req);
			}
			if (StringUtils.isEmpty(orderId)) {
				logger.error("创建订单失败平台订单编号为空");
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
//            e.printStackTrace();
//            logger.error(e.toString());
			//如果抛出异常,把redis回滚
			logger.error("库存集合:{}", list.toString());
			if (CollectionUtils.isNotEmpty(list)) {
				for (Map<String, String> map : list) {
					String cache_key_product_sku_sale = map.get("CACHE_KEY_PRODUCT_SKU_SALE_TOTAL");
					String CACHE_KEY_PRODUCT_SALE = map.get("CACHE_KEY_PRODUCT_SALE_TOTAL");
					String CACHE_KEY_PRODUCT_CENTRE_SKU_SALE = map.get("CACHE_KEY_PRODUCT_CENTRE_SKU_SALE_TOTAL");
					String CACHE_KEY_PRODUCT_CENTRE_SALE = map.get("CACHE_KEY_PRODUCT_CENTRE_SALE_TOTAL");
					if (cache_key_product_sku_sale != null) {
						logger.error("创建订单失败平台sku:{}", map.get("CACHE_KEY_PRODUCT_SKU_SALE"));
						localRedis.increamNum(map.get("CACHE_KEY_PRODUCT_SKU_SALE"), -Integer.valueOf(cache_key_product_sku_sale));
					}
					if (CACHE_KEY_PRODUCT_SALE != null) {
						logger.error("创建订单失败平台:{}", map.get("CACHE_KEY_PRODUCT_SALE"));
						localRedis.increamNum(map.get("CACHE_KEY_PRODUCT_SALE"), -Integer.valueOf(CACHE_KEY_PRODUCT_SALE));
					}
					if (CACHE_KEY_PRODUCT_CENTRE_SKU_SALE != null) {
						logger.error("创建订单失败站点sku:{}", map.get("CACHE_KEY_PRODUCT_CENTRE_SKU_SALE"));
						localRedis.increamNum(map.get("CACHE_KEY_PRODUCT_CENTRE_SKU_SALE"), -Integer.valueOf(CACHE_KEY_PRODUCT_CENTRE_SKU_SALE));
					}
					if (CACHE_KEY_PRODUCT_CENTRE_SALE != null) {
						logger.error("创建订单失败站点:{}", map.get("CACHE_KEY_PRODUCT_CENTRE_SALE"));
						localRedis.increamNum(map.get("CACHE_KEY_PRODUCT_CENTRE_SALE"), -Integer.valueOf(CACHE_KEY_PRODUCT_CENTRE_SALE));
					}
				}
			}
			if (e instanceof BDException) {
				throw e;
			} else {
				throw new BDException(BusinessCode.CREATE_ORDER_ERROR);
			}

		}
		return orderId;
	}

	/**
	 * 校验库存，封装订单商品对象,创建订单,发送消息
	 *
	 * @param member
	 * @param
	 * @param products
	 * @param sname
	 * @param mobile
	 * @param houseNo
	 * @param couponId
	 * @param address
	 * @return
	 */
	private String newCheckStock(Member member, List<MemberCartVo> products, String sname, String mobile, String houseNo, List list, Long couponId,
								 String address, String alldweight, String dispatchid, String dispatchprice, String iscomment,
								 Integer isSpellgroup, Long orderId, Long promoter, String appointmentName, String appointmentMobile,
								 Date appointmentDate, String seatNum, Integer cateringType, Integer dispatchtype, Long clerkId, Integer orderType,
								 Long addressId, Long teamId, Integer groupRules, Integer portType, Long shareMid, String shareOpenId) throws ParseException {

		logger.info("---进入普通订单新增---");
		Member teamLeader = null;

		//没有选门店
		if (teamId != null) {
			teamLeader = memberService.getByKey(teamId);
			if (teamLeader == null) {
				throw new BDException(BusinessCode.MEMBER_NOT_BIND_TEAM);
			}
		}
		List<Centre> centres = centreService.listAllCentres();
		if (CollectionUtils.isEmpty(centres)) {
			logger.info("not found centre info! auto check order delivery end...");
			return null;
		}
		Address deliveryAddress = null;
		if (addressId != null) {
			deliveryAddress = addressService.getByKey(addressId);
		}

		String payNo = null;
		String resOrderId = null;
		//TradeConfig tradeConfig=null;
		//TradeConfig tradeConfig = configService.getTradeConfig(null);
		for (Centre centre : centres) {
			//centreID不匹配，则跳过
			List<MemberCartVo> collect = products.stream().filter(MemberCartVo -> MemberCartVo.getCentreId().toString().equals(centre.getCentreId().toString())).collect(Collectors.toList());
			if (CollectionUtils.isEmpty(collect)) {
				continue;
			}
			Order order = new Order();
			BigDecimal orderPrice = new BigDecimal(0d);
			BigDecimal goodsPrice = new BigDecimal(0d);
			BigDecimal payIntegral = BigDecimal.ZERO;

			Integer goodstotal = 0;
			BigDecimal headcommission = new BigDecimal(0d);
			BigDecimal allweight = new BigDecimal(0d);
			//用户推荐人佣金
			BigDecimal usercommission = new BigDecimal(0d);
			//用户推荐人上级佣金
			BigDecimal superusercommission = new BigDecimal(0d);
			Long centreId = null;
			String orderSn = getSn("D");
			if (payNo == null) {
				String sn = DateUtils.format(new Date(), "ddHHmmss");
				payNo = "X_OC_".concat(orderSn).concat("_").concat(sn);
			}
			List<OrderProduct> ops = new ArrayList<>();
			List<ProductCentre> productCentreList = new ArrayList<>();
			Map<String, String> skuMap = new HashMap<>(16);
			//版本推荐人
			Member referralsMenber = null;

			//赠送的积分
			Integer getCredit = 0;

			for (MemberCartVo mc : collect) {

				Long centreProductId = mc.getProductId();
				ProductCentre pc = productCentreService.getByKeyWithCache(centreProductId);
				if (pc == null) {
					throw new BDException(BusinessCode.ORDER_PRODUCTS_ERROR);
				}
				productCentreList.add(pc);
				skuMap.put(pc.getId().toString(), mc.getSpecs());
				if (null == teamLeader) {
					teamLeader = memberService.getByKey(pc.getLiansuoid());
				}
				if (pc.getMaxbuy() > 0 && pc.getMaxbuy() < mc.getTotal()) {
					throw new BDException(BusinessCode.BUY_MAX_TOO_MANY);
				}
				centreId = pc.getCentreId();
				int t = orderProductMapper.countMidProductNums(member.getId(), centreProductId);
				if (pc.getUsermaxbuy() > 0 && pc.getUsermaxbuy() <= t) {
					throw new BDException(BusinessCode.BUY_MAX_LG_TOO_MANY);
				}


				ProductSkuCentre skuCentre = null;
				OrderProduct op = new OrderProduct();
				op.setProductPackageFlag(pc.getProductPackageFlag());
				Long centreSkuId = mc.getSkuId();
				if (pc.getHasoption() != null && pc.getHasoption() == 1) {
					//有SKU
					if (mc.getSkuId() == null && ValidateUtil.isEmptyString(mc.getSpecs())) {
						throw new BDException(BusinessCode.ORDER_PRODUCT_SKU_ERROR);
					}
					skuCentre = productCentreService.getSkuByKeyWithCache(mc.getSkuId());
					if (null == skuCentre) {
						skuCentre = productCentreService.getSkuBySpecs(mc.getSpecs());
					}
					if (skuCentre == null) {
						throw new BDException(BusinessCode.ORDER_PRODUCT_SKU_ERROR);
					}
				}
				//校验商品库存
				Long platformProductId = pc.getProductId();
				Map<String, String> map = new HashMap<>();
				Integer total = mc.getTotal();
				if (platformProductId != null && platformProductId > 0) {
					//平台商品
					Product base = productService.getByKeyWithCache(platformProductId);
					if (base == null) {
						throw new BDException(BusinessCode.ORDER_PRODUCTS_ERROR);
					}
					//op.setSelProductId(base.getId());
					if (base.getHasoption() != null && base.getHasoption() == 1) {
						//平台带SKU商品
						ProductSku sku = productSkuService.getSkuByKeyWithCache(skuCentre.getSkuId());
						if (sku == null) {
							throw new BDException(BusinessCode.ORDER_PRODUCT_SKU_ERROR);
						}
						op.setSkuId(sku.getId());
						long sSale = localRedis.increamNum(CACHE_KEY_PRODUCT_SKU_SALE.concat(String.valueOf(sku.getId())), total);
						if (sku.getStock() < sSale) {
							logger.info("平台带SKU商品:{},销量已超过限制！扣减销量", sku.getTitle());
							localRedis.increamNum(CACHE_KEY_PRODUCT_SKU_SALE.concat(String.valueOf(sku.getId())), -total);
							throw new BDException(pc.getTitle().concat("已卖完,请删除该商品"));
						}
						map.put("CACHE_KEY_PRODUCT_SKU_SALE", CACHE_KEY_PRODUCT_SKU_SALE.concat(String.valueOf(sku.getId())));
						map.put("CACHE_KEY_PRODUCT_SKU_SALE_TOTAL", total.toString());
					}

					long sale = localRedis.increamNum(CACHE_KEY_PRODUCT_SALE.concat(String.valueOf(platformProductId)), total);
					if (base.getTotal() <= sale) {
						ProductCentre productCentre = new ProductCentre();
						productCentre.setDisplayorder(0);
						productCentre.setProductId(platformProductId);
						//修改排序
						productCentreMapper.updateProductCentre(productCentre);
					}
					if (base.getTotal() < sale) {
						localRedis.increamNum(CACHE_KEY_PRODUCT_SALE.concat(String.valueOf(platformProductId)), -total);
						throw new BDException(pc.getTitle().concat("已卖完,请删除该商品"));
					}
					map.put("CACHE_KEY_PRODUCT_SALE", CACHE_KEY_PRODUCT_SALE.concat(String.valueOf(platformProductId)));
					map.put("CACHE_KEY_PRODUCT_SALE_TOTAL", total.toString());
				} else {
					//商户自卖商品
					if (pc.getHasoption() != null && pc.getHasoption() == 1) {
						//有SKU
						op.setSkuId(skuCentre.getId());
						long sSale = localRedis.increamNum(CACHE_KEY_PRODUCT_CENTRE_SKU_SALE.concat(String.valueOf(centreSkuId)), total);
						if (skuCentre.getStock() < sSale) {
							localRedis.increamNum(CACHE_KEY_PRODUCT_CENTRE_SKU_SALE.concat(String.valueOf(centreSkuId)), -total);
							throw new BDException(pc.getTitle().concat("已卖完,请删除该商品"));
						}
						map.put("CACHE_KEY_PRODUCT_CENTRE_SKU_SALE", CACHE_KEY_PRODUCT_CENTRE_SKU_SALE.concat(String.valueOf(centreSkuId)));
						map.put("CACHE_KEY_PRODUCT_CENTRE_SKU_SALE_TOTAL", total.toString());
					}
					long sale = localRedis.increamNum(CACHE_KEY_PRODUCT_CENTRE_SALE.concat(String.valueOf(pc.getId())), total);
					if (pc.getTotal() <= sale) {
						ProductCentre productCentre = new ProductCentre();
						productCentre.setDisplayorder(0);
						productCentre.setId(pc.getId());
						//修改排序
						productCentreMapper.updateByPrimaryKeySelective(productCentre);
					}
					if (pc.getTotal() < sale) {
						localRedis.increamNum(CACHE_KEY_PRODUCT_CENTRE_SALE.concat(String.valueOf(pc.getId())), -total);
						throw new BDException(pc.getTitle().concat("已卖完,请删除该商品"));
					}
					map.put("CACHE_KEY_PRODUCT_CENTRE_SALE", CACHE_KEY_PRODUCT_CENTRE_SALE.concat(String.valueOf(pc.getId())));
					map.put("CACHE_KEY_PRODUCT_CENTRE_SALE_TOTAL", total.toString());
					//op.setSelProductId(pc.getId());
				}
				list.add(map);
				op.setCartId(mc.getId());
				op.setMid(member.getId());
				op.setOpenid(member.getOpenid());
				op.setSname(sname);
				op.setMobile(mobile);
				op.setNickname(member.getNickname());
				op.setProductId(pc.getId());
				op.setIsLiansuo(pc.getLiansuoid() == null ? 0 : 1);
				op.setSelProductId(pc.getProductId());
				op.setProductCode(pc.getGoodscode());
				op.setTotal(mc.getTotal());
				op.setThumb(pc.getThumb());
				op.setPayIntegral(pc.getConsumptionIntegral());
				if (null != pc.getProductId() && pc.getProductId() > 0) {
					op.setBaseproductid(String.valueOf(pc.getProductId()));
				}

				BigDecimal marketPrice = BigDecimal.ZERO;

				marketPrice = pc.getMarketprice();

				//vip商户数据集合
				List<String> strlist = Arrays.asList(member.getVipofcentreId().split("-"));
				//用户是这个商户的vip
				if (member.getIsVip() == 1 && strlist.indexOf(centre.getCentreId().toString()) != -1) {
					{
						if (pc.getVipprice() != null && pc.getVipprice().doubleValue() > 0 && pc.getIsvip() == 1) {
							marketPrice = pc.getVipprice();
						}
					}
				}
				op.setMarketprice(marketPrice);
				op.setCostprice(pc.getCostprice());
				op.setProductprice(pc.getProductprice());
				op.setWeight(pc.getWeight().multiply(BigDecimal.valueOf(mc.getTotal())));
				op.setShortTitle(pc.getShortTitle());
				op.setProductName(pc.getTitle());
				op.setSpecTitle(pc.getSpecTitle());
				op.setUnit(pc.getUnit());
				op.setCredit(0);
				op.setIscredits(0);
				if (pc.getCredit() > 0) {
					op.setCredit(new BigDecimal(pc.getCredit() * mc.getTotal()).intValue());
					op.setIscredits(1);
					getCredit = getCredit + op.getCredit();
				}

				op.setIsKuaidi(mc.getIsKuaidi());
				//门店佣金类型
				op.setHeadtype(pc.getHeadtype());
				op.setSuperiortype(pc.getSuperiortype());
				op.setHeadcommission(pc.getHeadcommission());

				op.setSuperiorcommission(pc.getSuperiorcommission());
				op.setUsertype(pc.getUsertype());
				op.setUsercommission(pc.getUsercommission());
				op.setSuperusertype(pc.getSuperusertype());
				op.setSuperusercommission(pc.getSuperusercommission());
				//多规格商品
				if (pc.getHasoption() == 1) {
					op.setOptionname(skuCentre.getTitle());
					op.setHeadtype(skuCentre.getHeadtype());
					op.setSuperiortype(pc.getSuperiortype());
					op.setHeadcommission(pc.getHeadcommission());
					op.setSuperiorcommission(pc.getSuperiorcommission());

					//普通多规格商品价格获取
					if (skuCentre.getMarketprice() != null) {
						op.setMarketprice(skuCentre.getMarketprice());
						if (member.getIsVip() == 1) {
							if (skuCentre.getVipprice() != null && skuCentre.getVipprice().doubleValue() > 0 && pc.getIsvip() == 1) {
								op.setMarketprice(skuCentre.getVipprice());
							}
						}
					}
					if (skuCentre.getProductprice() != null) {
						op.setProductprice(skuCentre.getProductprice());
					}
					if (skuCentre.getWeight() != null) {
						op.setWeight(skuCentre.getWeight().multiply(BigDecimal.valueOf(mc.getTotal())));
					}
					if (skuCentre.getCostprice() != null && skuCentre.getCostprice().compareTo(BigDecimal.ZERO) == 1) {
						op.setCostprice(skuCentre.getCostprice());
					}
					if (StringUtils.isNotEmpty(skuCentre.getThumb())) {
						op.setThumb(skuCentre.getThumb());
					}
				}
				//商品总价格=商品单价*商品数量，这里是实际支付的金额
				op.setPrice(op.getMarketprice().multiply(BigDecimal.valueOf(mc.getTotal())));
				if (pc.getIsKuaidi() == 0) {
					op.setProvince(teamLeader.gettProvince());
					op.setCity(teamLeader.gettCity());
					op.setDistrict(teamLeader.gettArea());
					op.setAddress(teamLeader.gettShopname());
				} else {
					op.setProvince(member.getProvince());
					op.setCity(member.getCity());
					op.setDistrict(member.getArea());
					op.setAddress(member.getAddress());
				}

				op.setSaddress(op.getProvince() + op.getCity() + op.getDistrict() + op.getAddress());
				op.settMid(teamLeader.getId());
				op.settNickname(teamLeader.getNickname());
				op.setTtMid(teamLeader.getUpTeamid());
				op.setTtNickname(teamLeader.getUpTeamname());
				op.setCommision1(calcHeadCommission(op.getHeadtype(), op.getHeadcommission(), op.getPrice(), op.getTotal()));
				op.setCommision2(new BigDecimal(0));
				if (teamLeader.getUpTeamid() != null) {
					op.setCommision2(calcHeadCommission(op.getSuperiortype(), op.getSuperiorcommission(), op.getPrice(), op.getTotal()));
				}
				//用户推荐佣金
				op.setCommision5(new BigDecimal(0));
				//用户有推荐人
				if (member.getUserid() != null) {
					op.setCommision5(calcHeadCommission(pc.getUsertype(),
							pc.getUsercommission(), op.getPrice(), op.getTotal()));
				}
				//用户推荐人上级佣金
				op.setCommision6(new BigDecimal(0));
				//用户有推荐人上级
				if (member.getUpUserid() != null) {
					op.setCommision6(calcHeadCommission(pc.getSuperusertype(),
							pc.getSuperusercommission(), op.getPrice(), op.getTotal()));
				}
				//用户代理佣金
				op.setCommision7(new BigDecimal(0));
				//用户客户经理佣金
				op.setAccountManagerCommision(new BigDecimal(0));
				//商品分享佣金
				op.setProductShareCommision(new BigDecimal(0));
				if (shareMid != null && shareMid != 0L) {
					Member shareMember = memberService.getByKey(shareMid);
					op.setProductShareMemberId(shareMember.getId()); //设置商品分享用户id
					//商品分享佣金
					op.setProductShareCommision(calcProductShareCommission(op.getPrice(), centreId));
				}

				//商品分享佣金(openId直播分享类型单独参数)
				op.setProductShareOpenIdCommision(new BigDecimal(0));
				if (StringUtils.isNotEmpty(shareOpenId)) {
					Member shareMember = memberService.getByAppOpenId(shareOpenId);
					op.setProductShareOpenIdMemberId(shareMember.getId()); //设置商品分享用户id
					//商品分享佣金
					op.setProductShareOpenIdCommision(calcProductShareCommission(op.getPrice(), centreId));
				}


				//门店店员佣金
				op.setCommision8(new BigDecimal(0));
				if (clerkId != null && clerkId != 0) {
					//门店店员佣金
					op.setCommision8(calcHeadCommission(pc.getClerkertype(),
							pc.getClerkercommission(), op.getPrice(), op.getTotal()));
				}

				op.setCommision3(new BigDecimal(0));
				op.setReferrals(Long.parseLong("0"));
				op.setCommision4(new BigDecimal(0));
				op.setAgentid(Long.parseLong("0"));
				op.setAvatar(member.getAvatar());
				op.setRealname(member.getRealname());
				op.setGongyiprice(pc.getGongyiprice().multiply(BigDecimal.valueOf(mc.getTotal())));
				op.settXiaoqu(teamLeader.gettXiaoqu());
				op.setOrdersn(orderSn);
				//用户推荐人
				op.setUserid(member.getUserid() == null ? 0 : member.getUserid());
				//用户推荐人上级
				op.setUpuserid(member.getUpUserid() == null ? 0 : member.getUpUserid());
				//用户推荐代理
				op.setUseragentid(0L);
				op.setUsername(member.getUserName() == null ? "" : member.getUserName());
				op.setUpusername(member.getUpuserName() == null ? "" : member.getUpuserName());
				op.setUseragentName("");
				//拼团订单
				if (isSpellgroup != null && isSpellgroup == 1) {
					//拼团状态 拼团中
					op.setSpellgroupStu(1);
				} else {
					//不是拼团商品
					op.setSpellgroupStu(0);
				}

				goodsPrice = goodsPrice.add(op.getPrice());
				payIntegral = payIntegral.add(op.getPayIntegral());
				goodstotal = goodstotal + op.getTotal();
				allweight = allweight.add(op.getWeight());
				if (clerkId != null && clerkId != 0) {
					//店员推荐的会员，只给店员佣金，其他的都没有佣金
					//8有佣金，1256就不参与分佣
					op.setCommision1(BigDecimal.ZERO);
					op.setCommision2(BigDecimal.ZERO);
					op.setCommision5(BigDecimal.ZERO);
					op.setCommision6(BigDecimal.ZERO);
				}
				headcommission = headcommission.add(op.getCommision1());
				usercommission = usercommission.add(op.getCommision5());
				superusercommission = superusercommission.add(op.getCommision6());

				//订单商品记录邮费
				BigDecimal postage = new BigDecimal(0);
				if (orderType.equals(6)) {
					op.setDispatchprice(postage);
				} else {
					ProductCentre productCentre = productCentreService.getProductDetail(mc.getProductId());
					if (productCentre.getFreeShipping().equals(0)) {
						op.setDispatchprice(new BigDecimal(0));
					} else if (productCentre.getFreeShipping().equals(1)) {
						postage = postage.add(productCentre.getSendprice().multiply(new BigDecimal(mc.getTotal())));
					}
					op.setDispatchprice(postage);
				}
				ops.add(op);
			}
			order.setHeadcommission(headcommission);
			order.setOrdersn(orderSn);
			BigDecimal discountPrice = null;
			if (couponId != null) {
				//计算优惠券金额
				discountPrice = this.calcTicketAmount(couponId, goodsPrice, centreId, productCentreList, cateringType, skuMap, new BigDecimal(dispatchprice));
				order.setDiscountprice(discountPrice);
				order.setTrId(discountPrice == null ? null : couponId);
				couponId = null;
			}

			order.setPayIntegral(payIntegral);
			//商品总价
			order.setGoodsprice(goodsPrice);
			//订单总价
			orderPrice = goodsPrice;
			//增加包装费用
			order.setOrderprice(orderPrice);
			//支付金额
			BigDecimal payPrice = orderPrice.subtract(order.getDiscountprice() == null ? BigDecimal.ZERO : order.getDiscountprice());
			if (payPrice.compareTo(BigDecimal.ZERO) <= 0) {
				payPrice = BigDecimal.ZERO;
			}
			order.setPayprice(payPrice);
			if (referralsMenber != null) {
				order.setReferrals(referralsMenber.getId() == null ? 0 : referralsMenber.getId());
			}
			order.setCentreId(centre.getCentreId());
			order.setGoodstotal(goodstotal);
			//用户信息
			order.setMid(member.getId());
			order.setOpenid(member.getOpenid());
			order.setNickname(member.getNickname());
			order.setAvatar(member.getAvatar());
			order.setRealname(member.getRealname());
			if (deliveryAddress != null) {//收货地址
				order.setProvince(deliveryAddress.getProvince());
				order.setCity(deliveryAddress.getCity());
				order.setDistrict(deliveryAddress.getArea());
				order.setAddress(deliveryAddress.getAddress() + deliveryAddress.getHouseNum());
				order.setSaddress(order.getCity() + order.getDistrict() + order.getAddress());
				order.setSname(deliveryAddress.getName());
				order.setMobile(deliveryAddress.getMobile());
			} else {
				order.setSname(sname);
				order.setMobile(mobile);
			}
			order.setOutTradeNo(payNo);
			order.setPayMerchantNo(order.getOutTradeNo());
			order.settXiaoqu(teamLeader.gettXiaoqu());
			order.settMid(teamLeader.getId());
			order.settNickname(teamLeader.getNickname());
			order.setTtMid(teamLeader.getUpTeamid());
			order.setTtNickname(teamLeader.getUpTeamname());
			order.setRemark(houseNo);
			order.setIscomment(iscomment);
			//拼团订单
			if (isSpellgroup != null && isSpellgroup == 1) {
				//发起人
				order.setPromoter(promoter);
				//拼团状态 拼团中
				order.setSpellgroupStu(1);
				order.setGroupRules(groupRules);
				//带发起人订单id
				if (orderId != null) {
					//发起人拼团订单id
					order.setSgorderId(orderId);
				}
			}
			//订单类型（取第一个商品的类型为准）
			ProductCentre orderTypeProduct = productCentreService.getByKeyWithCache(collect.get(0).getProductId());
			if (orderTypeProduct.getProductType() == 0 || orderTypeProduct.getProductType() == null) {
				order.setOrderType(orderType);
			} else if (orderTypeProduct.getProductType() == ProductType.Score.getType()) {
				order.setOrderType(ProductType.Normal.getType());
			} else {
				order.setOrderType(orderTypeProduct.getProductType());
			}

			order.setPortType(portType);
			int r = orderMapper.insertSelective(order);
			if (r < 0) {
				throw new BDException(BusinessCode.CREATE_ORDER_ERROR);
			} else {
				//创建定时任务
				createAutoCloseOrderTask(order.getOrdersn(), order.getId(), order.getCentreId());
			}

			resOrderId = order.getId().toString();

			for (OrderProduct op : ops) {
				op.setOrderid(order.getId());
			}
			//修改优惠券折扣 金额
			updateDiscountPrice(ops, order.getDiscountprice());

			int i = orderProductMapper.insertSelectiveBatch(ops);
			if (i < 0) {
				throw new BDException(BusinessCode.CREATE_ORDER_ERROR);
			}

			//拼团订单
			if (isSpellgroup != null && isSpellgroup == 1) {
				//不带发起人订单id 发起人是自己
				if (orderId == null) {
					Order record = new Order();
					//订单id
					record.setId(order.getId());
					//拼团发起人订单id
					record.setSgorderId(order.getId());
					//修改拼团人数
					orderMapper.updateByPrimaryKeySelective(record);
				}
			}
			if (order.getTrId() != null) {
				TicketRecord trResult = ticketRecordMapper.getByKey(order.getTrId());
				if (trResult != null) {
					TicketRecord tr = new TicketRecord();
					tr.setId(order.getTrId());
					tr.setUseTime(new Date());
					tr.setOrderId(order.getId());
					if (trResult.getCountUsed() + 1 >= trResult.getCount()) {
						tr.setStatus(TicketStatus.USED.getStatus());
					}
					tr.setCountUsed(trResult.getCountUsed() + 1);
					tr.setDeductAmount(order.getDiscountprice());
					ticketService.updateRecord(tr);

					tr.setTicketId(trResult.getTicketId());
					tr.setMid(trResult.getMid());
					ticketService.addRecordUseInfo(tr, 1, order.getId(), "订单提交，使用优惠券",new TicketRecordUse());
				}
			}

			PlatformConfig config1 = configService.getConfigByKey(ConfigKey.TRADE_CONFIG.name(), null);
			JSONObject configValue = JSONObject.parseObject(config1.getConfigValue());
			String string = configValue.getString("RocketMQ");
			Object object = null;
			if (StringUtils.isNotBlank(string)) {
				JSONObject parseObject = JSON.parseObject(string);
				object = parseObject.get("R_ORDER");
			}
			if (object != null && "1".equals(object.toString())) {
				OrderMQProducer.sendAsync(JSON.toJSONString(ops), "ORDER_TOPIC", "CANCEL_ORDER", order.getId().toString());
			} else {
				orderMq(ops, order.getId());
			}
		}
		logger.info("---结束普通订单新增---+订单编号：" + resOrderId);
		return resOrderId;
	}

	private String newCheckStock2(Member member, String sname, String mobile,
								  String houseNo, Long projectExpId, String address, String iscomment,
								  Long referrals, Integer isupgrade, Long clerkId, Integer serviceDays) {


		Member teamLeader = null;

		//没有选门店
		if (member.getUpshopTid() != null) {
			teamLeader = memberService.getByKey(member.getUpshopTid());
			if (teamLeader == null) {
				throw new BDException(BusinessCode.MEMBER_NOT_BIND_TEAM);
			}
		} else {
			teamLeader = member;
		}

		String payNo = null;
		String resOrderId = null;
		ProjectExpVo params = new ProjectExpVo();
		params.setType(0);
		params.setId(projectExpId);
		//得到版本
		ProjectExp projectExp = projectExpService.listProjectExp(params);
		//差价
		List<OrderProduct> ops = new ArrayList<>();
		OrderProduct op = new OrderProduct();
		Order order = new Order();
		BuyProjectVo buyProjectVo = this.calcProjectExpCharge(member, serviceDays, projectExp);

		op.setIsupgrade(buyProjectVo.getIsupgrade());
		order.setIsupgrade(buyProjectVo.getIsupgrade());


		String orderSn = getSn("D");
		if (payNo == null) {
			payNo = "X_OC_".concat(orderSn);
		}

		op.setMid(member.getId());
		op.setOpenid(member.getOpenid());
		op.setSname(sname);
		op.setMobile(mobile);
		op.setNickname(member.getNickname());
		op.setProjectexpId(projectExp.getId());
		op.setTotal(serviceDays);//服务天数
		op.setPrice(projectExp.getPrice());

		op.setMarketprice(projectExp.getPrice());
		op.setCostprice(projectExp.getPrice());
		op.setProductprice(projectExp.getPrice());

		op.setShortTitle(projectExp.getName());
		op.setProductName(projectExp.getName());
		op.setCredit(0);
		op.setIscredits(0);
		op.setHeadtype(0);
		op.setSuperiortype(0);
		op.setHeadcommission(new BigDecimal("0"));
		op.setSuperiorcommission(new BigDecimal("0"));

		op.setSaddress(op.getProvince() + op.getCity() + op.getDistrict() + op.getAddress());
		op.settMid(teamLeader.getId());
		op.settNickname(teamLeader.getNickname());
		op.setTtMid(teamLeader.getUpTeamid());
		op.setTtNickname(teamLeader.getUpTeamname());
		op.setCommision1(new BigDecimal(0));
		op.setCommision2(new BigDecimal(0));
		op.setCommision3(new BigDecimal(0));
		op.setCommision4(new BigDecimal(0));
		op.setCommision5(new BigDecimal(0));
		op.setCommision6(new BigDecimal(0));
		op.setCommision7(new BigDecimal(0));
		op.setAccountManagerCommision(new BigDecimal(0));//客户经理佣金
		op.setProductShareCommision(new BigDecimal(0));//商品分享佣金
		op.setProductShareOpenIdCommision(new BigDecimal(0));//商品分享佣金
		op.setCommision8(new BigDecimal(0));
		//续费总额
		BigDecimal goodsPrice = buyProjectVo.getPayPrice();

		if (buyProjectVo.getIsupgrade().equals(1)) {//从试用版更换为收费版本(开户佣金)
			//用户有推荐人
			if (member.getUserid() != null) {
				BigDecimal commision10 = buyProjectVo.getRefReward();
				op.setCommision10(commision10);
				op.setUserid(member.getUserid());
			}
		}


		op.setAvatar(member.getAvatar());
		op.setRealname(member.getRealname());
		op.settXiaoqu(teamLeader.gettXiaoqu());
		op.setOrdersn(orderSn);
		op.setOrderid(order.getId());
		op.setIsCentreord(1);
		op.setOpenid(member.getOpenid());
		op.setReferrals(referrals == null ? 0 : referrals);
		//代理人
		op.setAgentid(0L);
		op.setIsLiansuo(0);
		ops.add(op);

		BigDecimal orderPrice = goodsPrice;
		//只有按天收费，并且是第一次支付，才会把开户费加上
		if (buyProjectVo.getFirstBuy() && buyProjectVo.getChargeType() == CenterChargeType.DAY.getType()) {
			orderPrice = orderPrice.add(buyProjectVo.getRemovePrice());
		}

		order.setOrderprice(orderPrice);
		order.setPayprice(orderPrice);
		order.setGoodsprice(goodsPrice);

		order.setReferrals(referrals == null ? 0 : referrals);
		order.setHeadcommission(new BigDecimal(0));
		order.setOrdersn(orderSn);

		order.setCentreId(member.getCentreId());
		order.setGoodstotal(1);
		order.setMid(member.getId());
		order.setOpenid(member.getOpenid());
		order.setNickname(member.getNickname());
		order.setAvatar(member.getAvatar());
		order.setRealname(member.getRealname());
		order.setProvince(teamLeader.gettProvince());
		order.setCity(teamLeader.gettCity());
		order.setDistrict(teamLeader.gettArea());
		order.setAddress(teamLeader.gettShopname());
		order.setSaddress(order.getProvince() + order.getCity() + order.getDistrict() + order.getAddress());
		order.setOutTradeNo(payNo);
		order.setPayMerchantNo(order.getOutTradeNo());
		order.setSname(sname);
		order.setMobile(mobile);
		order.settXiaoqu(teamLeader.gettXiaoqu());
		order.settMid(teamLeader.getId());
		order.settNickname(teamLeader.getNickname());
		order.setTtMid(teamLeader.getUpTeamid());
		order.setTtNickname(teamLeader.getUpTeamname());
		order.setRemark(houseNo);
		order.setIscomment(iscomment);
		order.setIsCentreord(1);
		order.setOrderType(0);
		int r = orderMapper.insertSelective(order);

		if (r < 0) {
			throw new BDException(BusinessCode.CREATE_ORDER_ERROR);
		}
		resOrderId = order.getId().toString();

		op.setOrderid(order.getId());
		op.setIsCentreord(1);
		op.setOpenid(member.getOpenid());
		op.setReferrals(referrals == null ? 0 : referrals);
		logger.info("============openid" + member.getOpenid());
		int i = orderProductMapper.insertSelective(op);

		if (i < 0) {
			throw new BDException(BusinessCode.CREATE_ORDER_ERROR);
		}

		PlatformConfig config1 = configService.getConfigByKey(ConfigKey.TRADE_CONFIG.name(), null);
		JSONObject configValue = JSONObject.parseObject(config1.getConfigValue());
		String string = configValue.getString("RocketMQ");
		Object object = null;
		if (StringUtils.isNotBlank(string)) {
			JSONObject parseObject = JSON.parseObject(string);
			object = parseObject.get("R_ORDER");
		}
		if (object != null && "1".equals(object.toString())) {
			OrderMQProducer.sendAsync(JSON.toJSONString(ops), "ORDER_TOPIC", "CANCEL_ORDER", order.getId().toString());
		} else {
			orderMq(ops, order.getId());
		}

		return resOrderId;
	}

	/**
	 * 超级店主订单创建
	 *
	 * @param member
	 * @param sname
	 * @param mobile
	 * @param houseNo
	 * @param address
	 * @return
	 */
	private String newCheckStock3(Member member, String sname, String mobile,
								  String houseNo, String address, String iscomment,
								  Long referrals, Long clerkId) {


		Member teamLeader = null;

		//没有选门店
		if (member.getUpshopTid() != null) {
			teamLeader = memberService.getByKey(member.getUpshopTid());
			if (teamLeader == null) {
				throw new BDException(BusinessCode.MEMBER_NOT_BIND_TEAM);
			}
		} else {
			teamLeader = member;
		}
		String resOrderId = null;

		List<OrderProduct> ops = new ArrayList<>();
		OrderProduct op = new OrderProduct();
		Order order = new Order();
		String orderSn = getSn("D");
		String payNo = "X_OC_".concat(orderSn);
		//查询升级vip需要的费用
		TradeConfig tradeConfig = configService.getTradeConfig(null);
		BigDecimal money = BigDecimal.ZERO;
		if (tradeConfig != null && tradeConfig.getSuperShopkeeperPrice() != null) {
			money = BigDecimal.valueOf(tradeConfig.getSuperShopkeeperPrice());
		}

		op.setMid(member.getId());
		op.setOpenid(member.getOpenid());
		op.setSname(sname);
		op.setMobile(mobile);
		op.setNickname(member.getNickname());
		op.setTotal(1);
		op.setPrice(money);

		op.setMarketprice(money);
		op.setCostprice(money);
		op.setProductprice(money);

		op.setShortTitle("升级为超级店主");
		op.setProductName("升级为超级店主");
		op.setCredit(0);
		op.setIscredits(0);
		op.setHeadtype(0);
		op.setSuperiortype(0);
		op.setHeadcommission(new BigDecimal("0"));
		op.setSuperiorcommission(new BigDecimal("0"));

		op.setSaddress(op.getProvince() + op.getCity() + op.getDistrict() + op.getAddress());
		op.settMid(teamLeader.getId());
		op.settNickname(teamLeader.getNickname());
		op.setTtMid(teamLeader.getUpTeamid());
		op.setTtNickname(teamLeader.getUpTeamname());
		op.setCommision1(new BigDecimal(0));
		op.setCommision2(new BigDecimal(0));
		op.setCommision3(new BigDecimal(0));
		op.setCommision4(new BigDecimal(0));
		op.setCommision5(new BigDecimal(0));
		op.setCommision6(new BigDecimal(0));
		op.setCommision7(new BigDecimal(0));
		op.setAccountManagerCommision(new BigDecimal(0));//客户经理佣金
		op.setProductShareCommision(new BigDecimal(0));//商品分享佣金
		op.setProductShareOpenIdCommision(new BigDecimal(0));//商品分享佣金
		op.setCommision8(new BigDecimal(0));

		op.setAvatar(member.getAvatar());
		op.setRealname(member.getRealname());
		op.settXiaoqu(teamLeader.gettXiaoqu());
		op.setOrdersn(orderSn);
		op.setOrderid(order.getId());
		op.setIsCentreUpgrade(1);
		op.setOpenid(member.getOpenid());
		op.setReferrals(referrals == null ? 0 : referrals);
		//代理人
		op.setAgentid(0L);
		op.setIsLiansuo(0);
		ops.add(op);

		order.setOrderprice(money);
		order.setPayprice(money);
		order.setGoodsprice(money);

		order.setReferrals(referrals == null ? 0 : referrals);
		order.setHeadcommission(new BigDecimal(0));
		order.setOrdersn(orderSn);

		order.setCentreId(member.getCentreId());
		order.setGoodstotal(1);
		order.setMid(member.getId());
		order.setOpenid(member.getOpenid());
		order.setNickname(member.getNickname());
		order.setAvatar(member.getAvatar());
		order.setRealname(member.getRealname());
		order.setProvince(teamLeader.gettProvince());
		order.setCity(teamLeader.gettCity());
		order.setDistrict(teamLeader.gettArea());
		order.setAddress(teamLeader.gettShopname());
		order.setSaddress(order.getProvince() + order.getCity() + order.getDistrict() + order.getAddress());
		order.setOutTradeNo(payNo);
		order.setPayMerchantNo(order.getOutTradeNo());
		order.setSname(sname);
		order.setMobile(mobile);
		order.settXiaoqu(teamLeader.gettXiaoqu());
		order.settMid(teamLeader.getId());
		order.settNickname(teamLeader.getNickname());
		order.setTtMid(teamLeader.getUpTeamid());
		order.setTtNickname(teamLeader.getUpTeamname());
		order.setRemark(houseNo);
		order.setIscomment(iscomment);
		order.setIsCentreUpgrade(1);
		order.setOrderType(0);
		int r = orderMapper.insertSelective(order);

		if (r < 0) {
			throw new BDException(BusinessCode.CREATE_ORDER_ERROR);
		}
		resOrderId = order.getId().toString();

		op.setOrderid(order.getId());
		op.setIsCentreUpgrade(1);
		op.setOpenid(member.getOpenid());
		op.setReferrals(referrals == null ? 0 : referrals);
		logger.info("============openid" + member.getOpenid());
		int i = orderProductMapper.insertSelective(op);

		if (i < 0) {
			throw new BDException(BusinessCode.CREATE_ORDER_ERROR);
		}

		PlatformConfig config1 = configService.getConfigByKey(ConfigKey.TRADE_CONFIG.name(), null);
		JSONObject configValue = JSONObject.parseObject(config1.getConfigValue());
		String string = configValue.getString("RocketMQ");
		Object object = null;
		if (StringUtils.isNotBlank(string)) {
			JSONObject parseObject = JSON.parseObject(string);
			object = parseObject.get("R_ORDER");
		}
		if (object != null && "1".equals(object.toString())) {
			OrderMQProducer.sendAsync(JSON.toJSONString(ops), "ORDER_TOPIC", "CANCEL_ORDER", order.getId().toString());
		} else {
			orderMq(ops, order.getId());
		}

		return resOrderId;
	}


	/**
	 * 门店申请订单创建
	 */
	private String newCheckStock4(Member member, String sname, String mobile,
								  OrderReq req) {
		logger.info("=======进入门店申请订单======");
		logger.info("=======req.getTerminalId()======"+req.getTerminalId());
		String resOrderId = null;

		List<OrderProduct> ops = new ArrayList<>();
		OrderProduct op = new OrderProduct();
		Order order = new Order();
		String orderSn = getSn("D");
		String payNo = "X_OC_".concat(orderSn);
		//查询门店申请需要的费用
		BigDecimal payPrice = BigDecimal.ZERO;
		if (ValidateUtil.isNotEmptyString(req.getTerminalId())) {
			String[] strIds = req.getTerminalId().split(",");
			List<String> list = Arrays.asList(strIds);
			Collection<Long> idCollection = new ArrayList<>();
			list.forEach(item -> {
				idCollection.add(Long.valueOf(item));
			});
			List<CentreTerminal> centreTerminalList = centreTerminalMapper.selectByIdIn(idCollection, member.getCentreId());
			if (ValidateUtil.isEmptyCollection(centreTerminalList)) {
				centreTerminalList = centreTerminalMapper.selectByIdIn(idCollection, null);
			}
			if (centreTerminalList == null) {
				throw new BDException("终端配置错误，请联系管理员！");
			}
			for (CentreTerminal centreTerminal : centreTerminalList) {
				logger.info("=======金额为"+centreTerminal.getStoresPay()+"======");
				payPrice = payPrice.add(centreTerminal.getStoresPay());
			}
		}
		logger.info("=======总金额为"+payPrice+"======");

		op.setMid(member.getId());
		op.setOpenid(member.getOpenid());
		op.setSname(sname);
		op.setMobile(mobile);
		op.setNickname(member.getNickname());
		op.setTotal(1);
		op.setPrice(payPrice);

		op.setMarketprice(payPrice);
		op.setCostprice(payPrice);
		op.setProductprice(payPrice);

		op.setShortTitle("门店申请");
		op.setProductName("门店申请");
		op.setCredit(0);
		op.setIscredits(0);
		op.setHeadtype(0);
		op.setSuperiortype(0);
		op.setHeadcommission(new BigDecimal("0"));
		op.setSuperiorcommission(new BigDecimal("0"));

		op.setSaddress(op.getProvince() + op.getCity() + op.getDistrict() + op.getAddress());
		op.settMid(member.getId());
		op.settNickname(member.getNickname());
		op.setTtMid(member.getUpTeamid());
		op.setTtNickname(member.getUpTeamname());
		op.setCommision1(new BigDecimal(0));
		op.setCommision2(new BigDecimal(0));
		op.setCommision3(new BigDecimal(0));
		op.setCommision4(new BigDecimal(0));
		op.setCommision5(new BigDecimal(0));
		op.setCommision6(new BigDecimal(0));
		op.setCommision7(new BigDecimal(0));
		op.setAccountManagerCommision(new BigDecimal(0));//客户经理佣金
		op.setProductShareCommision(new BigDecimal(0));//商品分享佣金
		op.setProductShareOpenIdCommision(new BigDecimal(0));//商品分享佣金
		op.setCommision8(new BigDecimal(0));

		op.setAvatar(member.getAvatar());
		op.setRealname(member.getRealname());
		op.settXiaoqu(member.gettXiaoqu());
		op.setOrdersn(orderSn);
		op.setOrderid(order.getId());
		op.setIsCentreUpgrade(0);
		op.setOpenid(member.getOpenid());
		//代理人
		op.setAgentid(0L);
		op.setIsLiansuo(0);
		op.setIsStores(1);
		op.setTerminalId(req.getTerminalId());
		ops.add(op);

		order.setOrderprice(payPrice);
		order.setPayprice(payPrice);
		order.setGoodsprice(payPrice);

		order.setHeadcommission(new BigDecimal(0));
		order.setOrdersn(orderSn);

		order.setCentreId(member.getCentreId());
		order.setGoodstotal(1);
		order.setMid(member.getId());
		order.setOpenid(member.getOpenid());
		order.setNickname(member.getNickname());
		order.setAvatar(member.getAvatar());
		order.setRealname(member.getRealname());
		order.setProvince(member.gettProvince());
		order.setCity(member.gettCity());
		order.setDistrict(member.gettArea());
		order.setAddress(member.gettShopname());
		order.setSaddress(order.getProvince() + order.getCity() + order.getDistrict() + order.getAddress());
		order.setOutTradeNo(payNo);
		order.setPayMerchantNo(order.getOutTradeNo());
		order.setSname(sname);
		order.setMobile(mobile);
		order.settXiaoqu(member.gettXiaoqu());
		order.settMid(member.getId());
		order.settNickname(member.getNickname());
		order.setTtMid(member.getUpTeamid());
		order.setTtNickname(member.getUpTeamname());
		order.setRemark(req.getHouseNo());
		order.setIscomment(req.getIscomment());
		order.setIsCentreUpgrade(0);
		order.setOrderType(0);
		order.setIsStores(1);
		order.setTerminalId(req.getTerminalId());
		int r = orderMapper.insertSelective(order);

		if (r < 0) {
			throw new BDException(BusinessCode.CREATE_ORDER_ERROR);
		}
		resOrderId = order.getOutTradeNo();

		op.setOrderid(order.getId());
		op.setIsStores(1);
		op.setOpenid(member.getOpenid());
		logger.info("============openid" + member.getOpenid());
		int i = orderProductMapper.insertSelective(op);

		if (member.getReferrerMid() != null) {
			Member referrerMember = memberService.getByKey(member.getReferrerMid());
			if (referrerMember.getIsteam() == 3) {
				CommissionLog commissionLog = new CommissionLog();
				//门店推荐门店佣金
				commissionLog.setMid(referrerMember.getId());
				commissionLog.setOrderId(order.getId());
				commissionLog.setOrderProductId(op.getId());
				//门店推荐门店佣金
				commissionLog.setType(CommissionLogType.storeRecommendStoreCommission.getType());
				commissionLog.setCreateTime(new Date());
				commissionLog.setCommission(calcStoreCommission(payPrice, req.getCenterId(), "storeRecommendStoreCommission"));
				commissionLog.setCentreId(order.getCentreId());
				commissionLogMapper.insertSelective(commissionLog);
			} else if (referrerMember.getIsVip() == 1) {
				CommissionLog commissionLog = new CommissionLog();
				//门店推荐门店佣金
				commissionLog.setMid(referrerMember.getId());
				commissionLog.setOrderId(order.getId());
				commissionLog.setOrderProductId(op.getId());
				//门店推荐门店佣金
				commissionLog.setType(CommissionLogType.makerRecommendStoreCommission.getType());
				commissionLog.setCreateTime(new Date());
				commissionLog.setCommission(calcStoreCommission(payPrice, req.getCenterId(), "makerRecommendStoreCommission"));
				commissionLog.setCentreId(order.getCentreId());
				commissionLogMapper.insertSelective(commissionLog);
			}

		}


		if (i < 0) {
			throw new BDException(BusinessCode.CREATE_ORDER_ERROR);
		}

		PlatformConfig config1 = configService.getConfigByKey(ConfigKey.TRADE_CONFIG.name(), null);
		JSONObject configValue = JSONObject.parseObject(config1.getConfigValue());
		String string = configValue.getString("RocketMQ");
		Object object = null;
		if (StringUtils.isNotBlank(string)) {
			JSONObject parseObject = JSON.parseObject(string);
			object = parseObject.get("R_ORDER");
		}
		if (object != null && "1".equals(object.toString())) {
			OrderMQProducer.sendAsync(JSON.toJSONString(ops), "ORDER_TOPIC", "CANCEL_ORDER", order.getId().toString());
		} else {
			orderMq(ops, order.getId());
		}

		return resOrderId;
	}

	/**
	 * 计算门店佣金
	 *
	 * @param headtype
	 * @param headcommission
	 * @param price
	 * @param total
	 * @return
	 */
	private BigDecimal calcHeadCommission(Integer headtype, BigDecimal headcommission, BigDecimal price, Integer total) {
		if (headtype == null || headcommission == null) {
			return new BigDecimal(0);
		}
		if (headtype == 0) {
			if (total == null) {
				return new BigDecimal(0);
			}
			return headcommission.multiply(BigDecimal.valueOf(total));
		} else {
			if (price == null) {
				return new BigDecimal(0);
			}
			return price.multiply(headcommission).divide(BigDecimal.valueOf(100), BigDecimal.ROUND_HALF_UP);
		}
	}

	/**
	 * 计算用户商品分享佣金
	 *
	 * @param price
	 * @param centerId
	 * @return
	 */
	private BigDecimal calcProductShareCommission(BigDecimal price, Long centerId) {
		//得到佣金配置
		PlatformConfig config = configService.getConfigByKey(ConfigKey.COMMIS_CONFIG.name(), centerId);
		if (config != null) {
			if (StringUtils.isNotEmpty(config.getConfigValue())) {
				Map<String, Object> jsonToMap = JSONObject.parseObject(config.getConfigValue());
				try {
					//Double agenttype = Double.valueOf(jsonToMap.get("agenttype").toString());
					Double productShareCommission = Double.valueOf(jsonToMap.get("productShareCommission").toString());
					if (productShareCommission != null) {
						//佣金比例
						BigDecimal ratio = new BigDecimal(productShareCommission).
								divide(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_DOWN);
						//返回佣金 保留2位小数不四舍五入
						return price.multiply(ratio)
								.setScale(2, BigDecimal.ROUND_DOWN);
					} else {
						return new BigDecimal(0);
					}
				} catch (Exception e) {
					logger.info("计算商品分享佣金错误");
					return new BigDecimal(0);
				}
			}
		}
		return new BigDecimal(0);
	}


	@Override
	public void sendGZHProductGeneralMsg(Long centreId, Long mid, Map<String, String> map, String url) {
		PlatformConfig platformConfig = configService.getConfigByKey(ConfigKey.GZHTEMPLATE_CONFIG.name(), centreId);
		TemplateGZHConfig templateGZHConfig = null;
		if (platformConfig == null) {
			logger.info("该商户并未配置公众号模板====null");
			;
		} else {
			templateGZHConfig = JSON.parseObject(platformConfig.getConfigValue(), TemplateGZHConfig.class, Feature.OrderedField);
		}
		//得到用户信息
		Member mem = memberService.getByKey(mid);
		if (mem == null) {
			logger.info("用户不存在！");
		}
		WxNotifyParam notifyParam = new WxNotifyParam();
		List<TemplateParam> paras = new ArrayList<>();

		InformationGZHTemplate informationGZHTemplate = null;
		if (templateGZHConfig != null) {
			if (ValidateUtil.isNotEmptyString(templateGZHConfig.getFreeChargeCallbackIdGZH())) {
				informationGZHTemplate = informationGZHTemplateService.findDetail(Long.parseLong(templateGZHConfig.getFreeChargeCallbackIdGZH()));
			}
		}

		//模板id
		Member member = memberMapper.selectByPrimaryKey(mid);
		if (informationGZHTemplate != null && ValidateUtil.isNotEmptyString(templateGZHConfig.getWxFreeChargeCallbackIdGZH()) && ValidateUtil.isNotEmptyObjectOrString(member.getOpenid())) {
			//模板消息
			HashMap<String, Object> result = JSON.parseObject(informationGZHTemplate.getTemplateValue(), LinkedHashMap.class, Feature.OrderedField);
			HashMap<String, Object> resultEntity = JSON.parseObject(informationGZHTemplate.getTemplateEntity(), LinkedHashMap.class, Feature.OrderedField);
			if (result == null) {
				throw new BDException("公众号消息模板参数不存在！");
			} else {

				/*
				通过Map.keySet遍历key和value：
				逻辑解释:
				map里存储的是供选择使用的键值对,
				paras里存的是模板需要的键值对,
				paras的key,为微信服务平台提供的代替换字段名,value为字段名对应的具体值(实体属性)
				 */
				for (String key : result.keySet()) {
					paras.add(new TemplateParam(result.get(key).toString(), map.get(resultEntity.get(key).toString())));
				}

				//三个参数:类型 商户id 链接
				notifyParam.setMessageType(WxMessageType.MESSAGE_TYPE_TEMPLATE.getType());//模板消息
				notifyParam.setCenterId(centreId);
				notifyParam.setUrl(url);
				//三个参数:模板id 公众号端 会员openid
				notifyParam.setTemplateId(templateGZHConfig.getWxFreeChargeCallbackIdGZH());
				notifyParam.setTeminal(WxTerminal.TERMINAL_GZH.getTerminal());
				notifyParam.setGzhOpenId(member.getOpenid());

				//内容字段
				Map<String, String> notifyParamItems = new HashMap<>();
				for (TemplateParam templateParam : paras) {
					notifyParamItems.put(templateParam.getKey(), templateParam.getValue());
				}
				notifyParam.setItems(notifyParamItems);
				wxNotifyService.sendNotify(notifyParam);
			}
		} else {
			logger.info("公众号消息配置错误！");
		}
	}



	/**
	 * 创建自动关闭未付款订单任务
	 *
	 * @param orderSn
	 * @param orderId
	 */
	private void createAutoCloseOrderTask(String orderSn, Long orderId, Long centreId) {
		int closeMinute = 6;
		TradeConfig config = configService.getTradeConfig(centreId);
		if (config != null) {
			Integer min = config.getAutoCloseNoPayOrderMin();
			if (min != null) {
				closeMinute = min;
			}
		}
		quartzManager.addJob(orderSn, "ORDER", closeMinute, OrderNoPyJob.class, orderId);

	}

	/**
	 * 给每个商品添加平均折扣
	 *
	 * @param orderProductList
	 * @param discountPriceSum
	 * @return
	 */
	public void updateDiscountPrice(List<OrderProduct> orderProductList, BigDecimal discountPriceSum) {
		if (discountPriceSum == null) {
			return;
		}
		int size = orderProductList.size();
		//折扣金额  除以商品数量
		BigDecimal[] results = discountPriceSum.divideAndRemainder(BigDecimal.valueOf(size));
		//每个商品平均折扣
		BigDecimal averageDiscount = results[0];
		//余数
		BigDecimal remainder = results[1];

		BigDecimal surplusNum = BigDecimal.ZERO;
//		Map<Long,BigDecimal> discountPriceMap = new HashMap();
		int index = 1;
		for (OrderProduct orderProduct : orderProductList) {
			if (index == size) {
				averageDiscount = averageDiscount.add(remainder);
			}
//			discountPriceMap.put(orderProduct.getProductId(),averageDiscount);
			index++;

			BigDecimal price = orderProduct.getPrice();
			BigDecimal discountPrice = averageDiscount.add(surplusNum);
			if (discountPrice.compareTo(price) > 0) {
				surplusNum = discountPrice.subtract(price);
				discountPrice = price;
			} else {
				surplusNum = BigDecimal.ZERO;
			}

			orderProduct.setDiscountPrice(discountPrice);

		}
	}


	/**
	 * 计算门店开通分佣
	 *
	 * @return
	 */
	private BigDecimal calcStoreCommission(BigDecimal price, Long centerId, String commissionType) {
		//得到佣金配置
		PlatformConfig config = configService.getConfigByKey(ConfigKey.COMMIS_CONFIG.name(), centerId);
		if (config != null) {
			if (StringUtils.isNotEmpty(config.getConfigValue())) {
				Map<String, Object> jsonToMap = JSONObject.parseObject(config.getConfigValue());
				try {
					//Double agenttype = Double.valueOf(jsonToMap.get("agenttype").toString());
					Double productShareCommission = Double.valueOf(jsonToMap.get(commissionType).toString());
					if (productShareCommission != null) {
						//佣金比例
						BigDecimal ratio = new BigDecimal(productShareCommission).
								divide(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_DOWN);
						//返回佣金 保留2位小数不四舍五入
						return price.multiply(ratio)
								.setScale(2, BigDecimal.ROUND_DOWN);
					} else {
						return new BigDecimal(0);
					}
				} catch (Exception e) {
					logger.info("计算商品分享佣金错误");
					return new BigDecimal(0);
				}
			}
		}
		return new BigDecimal(0);
	}

	/**
	 * 订单不走mq
	 *
	 * @param ops
	 * @param orderId
	 */
	private void orderMq(List<OrderProduct> ops, Long orderId) {
		try {
			Order order = orderMapper.selectByPrimaryKey(orderId);
			if (null == order) {
				throw new BDException(BusinessCode.ORDER_INFO_ISNULL);
			}
			if (CollectionUtils.isEmpty(ops)) {
				throw new BDException(BusinessCode.ORDER_PRODUCTS_ISNULL);
			}
			logger.info("orderProducts:{},", JSON.toJSONString(ops));
			List<CommissionLog> commissionLogs = new ArrayList<>();
			//循环商品信息加销量
			for (OrderProduct orderProduct : ops) {
				//累计佣金
				if (orderProduct.getCommision1() != null && orderProduct.getCommision1().doubleValue() > 0) {//门店佣金
					CommissionLog commissionLog = new CommissionLog();
					commissionLog.setMid(order.gettMid());
					commissionLog.setOrderId(order.getId());
					commissionLog.setOrderProductId(orderProduct.getId());
					commissionLog.setType(1);
					commissionLog.setCreateTime(new Date());
					commissionLog.setCommission(orderProduct.getCommision1());
					commissionLog.setCentreId(order.getCentreId());
					commissionLogs.add(commissionLog);
				}
				if (orderProduct.getCommision2() != null && orderProduct.getCommision2().doubleValue() > 0) {//门店推荐人
					CommissionLog commissionLog = new CommissionLog();
					commissionLog.setMid(order.getTtMid());
					commissionLog.setOrderId(order.getId());
					commissionLog.setOrderProductId(orderProduct.getId());
					commissionLog.setType(2);
					commissionLog.setCreateTime(new Date());
					commissionLog.setCommission(orderProduct.getCommision2());
					commissionLog.setCentreId(order.getCentreId());
					commissionLogs.add(commissionLog);
				}
				if (orderProduct.getCommision3() != null && orderProduct.getCommision3().doubleValue() > 0) {
					CommissionLog commissionLog = new CommissionLog();
					//推荐人
					commissionLog.setMid(orderProduct.getReferrals());
					commissionLog.setOrderId(order.getId());
					commissionLog.setOrderProductId(orderProduct.getId());
					//站点推荐用户返佣
					commissionLog.setType(3);
					commissionLog.setCreateTime(new Date());
					commissionLog.setCommission(orderProduct.getCommision3());
					commissionLog.setCentreId(order.getCentreId());
					commissionLogs.add(commissionLog);
				}
				if (orderProduct.getCommision4() != null && orderProduct.getCommision4().doubleValue() > 0) {//代理
					CommissionLog commissionLog = new CommissionLog();
					//推荐人
					commissionLog.setMid(orderProduct.getAgentid());
					commissionLog.setOrderId(order.getId());
					commissionLog.setOrderProductId(orderProduct.getId());
					//站点推荐用户返佣
					commissionLog.setType(4);
					commissionLog.setCreateTime(new Date());
					commissionLog.setCommission(orderProduct.getCommision4());
					commissionLog.setCentreId(order.getCentreId());
					commissionLogs.add(commissionLog);
				}
				if (orderProduct.getCommision5() != null && orderProduct.getCommision5().doubleValue() > 0) {//用户推荐人
					CommissionLog commissionLog = new CommissionLog();
					//用户推荐人
					commissionLog.setMid(orderProduct.getUserid());
					commissionLog.setOrderId(order.getId());
					commissionLog.setOrderProductId(orderProduct.getId());
					//站点推荐用户返佣
					commissionLog.setType(5);
					commissionLog.setCreateTime(new Date());
					commissionLog.setCommission(orderProduct.getCommision5());
					commissionLog.setCentreId(order.getCentreId());
					commissionLogs.add(commissionLog);
				}
				if (orderProduct.getCommision6() != null && orderProduct.getCommision6().doubleValue() > 0) {//用户推荐人二级
					CommissionLog commissionLog = new CommissionLog();
					//用户推荐人上级
					commissionLog.setMid(orderProduct.getUpuserid());
					commissionLog.setOrderId(order.getId());
					commissionLog.setOrderProductId(orderProduct.getId());
					//站点推荐用户返佣
					commissionLog.setType(6);
					commissionLog.setCreateTime(new Date());
					commissionLog.setCommission(orderProduct.getCommision6());
					commissionLog.setCentreId(order.getCentreId());
					commissionLogs.add(commissionLog);
				}

				if (orderProduct.getCommision7() != null && orderProduct.getCommision7().doubleValue() > 0) {//用户代理
					CommissionLog commissionLog = new CommissionLog();
					//用户代理人
					commissionLog.setMid(orderProduct.getUseragentid());
					commissionLog.setOrderId(order.getId());
					commissionLog.setOrderProductId(orderProduct.getId());
					//站点推荐用户返佣
					commissionLog.setType(7);
					commissionLog.setCreateTime(new Date());
					commissionLog.setCommission(orderProduct.getCommision7());
					commissionLog.setCentreId(order.getCentreId());
					commissionLogs.add(commissionLog);
				}

				if (orderProduct.getAccountManagerCommision() != null && orderProduct.getAccountManagerCommision().doubleValue() > 0) {//用户客户经理佣金
					CommissionLog commissionLog = new CommissionLog();
					//用户客户经理
					commissionLog.setMid(orderProduct.getBelongAccountManagerId());
					commissionLog.setOrderId(order.getId());
					commissionLog.setOrderProductId(orderProduct.getId());
					//客户经理用户返佣
					commissionLog.setType(CommissionLogType.AccountManagerCommission.getType());
					commissionLog.setCreateTime(new Date());
					commissionLog.setCommission(orderProduct.getAccountManagerCommision());
					commissionLog.setCentreId(order.getCentreId());
					commissionLogs.add(commissionLog);
				}

				if (orderProduct.getProductShareCommision() != null && orderProduct.getProductShareCommision().doubleValue() > 0) {//用户客户经理佣金
					CommissionLog commissionLog = new CommissionLog();
					//商品分享佣金
					commissionLog.setMid(orderProduct.getProductShareMemberId());
					commissionLog.setOrderId(order.getId());
					commissionLog.setOrderProductId(orderProduct.getId());
					//商品分享用户返佣
					commissionLog.setType(CommissionLogType.ProductShareCommission.getType());
					commissionLog.setCreateTime(new Date());
					commissionLog.setCommission(orderProduct.getProductShareCommision());
					commissionLog.setCentreId(order.getCentreId());
					commissionLogs.add(commissionLog);
				}

				if (orderProduct.getProductShareOpenIdCommision() != null && orderProduct.getProductShareOpenIdCommision().doubleValue() > 0) {//用户客户经理佣金
					CommissionLog commissionLog = new CommissionLog();
					//商品分享佣金
					commissionLog.setMid(orderProduct.getProductShareOpenIdMemberId());
					commissionLog.setOrderId(order.getId());
					commissionLog.setOrderProductId(orderProduct.getId());
					//商品分享用户返佣
					commissionLog.setType(CommissionLogType.ProductShareCommission.getType());
					commissionLog.setCreateTime(new Date());
					commissionLog.setCommission(orderProduct.getProductShareOpenIdCommision());
					commissionLog.setCentreId(order.getCentreId());
					commissionLogs.add(commissionLog);
				}



				//店员佣金
				if (orderProduct.getCommision8() != null && orderProduct.getCommision8().doubleValue() > 0) {
					CommissionLog commissionLog = new CommissionLog();
					commissionLog.setMid(order.gettMid());
					commissionLog.setOrderId(order.getId());
					commissionLog.setOrderProductId(orderProduct.getId());
					commissionLog.setType(8);
					commissionLog.setCreateTime(new Date());
					commissionLog.setCommission(orderProduct.getCommision1());
					commissionLog.setCentreId(order.getCentreId());
					commissionLogs.add(commissionLog);
				}
				//开户续费用户代理佣金
				if (orderProduct.getCommision9() != null && orderProduct.getCommision9().doubleValue() > 0) {
					CommissionLog commissionLog = new CommissionLog();
					//用户代理人
					commissionLog.setMid(orderProduct.getUseragentid());

					commissionLog.setOrderId(order.getId());
					commissionLog.setOrderProductId(orderProduct.getId());
					//站点推荐用户返佣
					commissionLog.setType(9);
					commissionLog.setCreateTime(new Date());
					commissionLog.setCommission(orderProduct.getCommision9());
					commissionLog.setCentreId(order.getCentreId());
					commissionLogs.add(commissionLog);
				}
				//开户用户推荐人佣金
				if (orderProduct.getCommision10() != null && orderProduct.getCommision10().doubleValue() > 0) {
					CommissionLog commissionLog = new CommissionLog();
					//用户推荐人
					commissionLog.setMid(orderProduct.getUserid());
					commissionLog.setOrderId(order.getId());
					commissionLog.setOrderProductId(orderProduct.getId());
					//站点推荐用户返佣
					commissionLog.setType(10);
					commissionLog.setCreateTime(new Date());
					commissionLog.setCommission(orderProduct.getCommision10());
					commissionLog.setCentreId(order.getCentreId());
					commissionLogs.add(commissionLog);
				}

				if (order.getIsCentreord() == null || order.getIsCentreord() == 0) {
					Integer total = orderProduct.getTotal();

					//拼团商品，修改拼团商品的库存
					if (order.getOrderType() == ProductType.Spellgroup.getType()) {
						int sr = 0;
						if (null == orderProduct.getSkuId()) {
							sr = marketingGroupService.changeStock(-total, orderProduct.getActivityId());
							if (sr < 1) {
								logger.error("----------------商户带SKU商品SKU:{},更新已售失败:{}", orderProduct.getSkuId(), total);
							}
						} else {
							sr = marketingGroupService.changeSkuStock(-total, orderProduct.getActivityId(), orderProduct.getSkuId());
							if (sr < 1) {
								logger.error("----------------商户商品ID:{},更新已售失败:{}", orderProduct.getProductId(), total);
							}
						}
					} else if (order.getOrderType() == ProductType.FreeCharge.getType()) {
						int sr = activityMapper.changeStock(-total, orderProduct.getProductId());
						if (sr < 1) {
							logger.error("----------------大礼包商品:{},更新已售失败:{}", orderProduct.getProductId(), total);
						}
					} else {
						//商户
						if (orderProduct.getSkuId() != null) {
							int sr = productCentreService.changeSkuStock(total, orderProduct.getSkuId());
							if (sr < 1) {
								logger.error("----------------商户带SKU商品SKU:{},更新已售失败:{}", orderProduct.getSkuId(), total);
							}
						}
						//更新累计销售数量
						int r = productCentreService.changeStock(total, orderProduct.getProductId());//华胜写的逻辑
						if (r < 1) {
							logger.error("----------------商户商品id:{}, 更新已售失败", orderProduct.getProductId());
						}
					}

					if (StringUtils.isNotBlank(orderProduct.getCartId())) {
						// 购物车
						logger.info("清空购物车:{},{},{}", orderProduct.getMid(), order.getCentreId(), orderProduct.getCartId());
						memberCartService.removeItemRedis(orderProduct.getMid(), order.getCentreId(), orderProduct.getCartId(), orderProduct.getIsKuaidi());
						logger.info("清空购物车完成");
					}

				}
			}

			if (CollectionUtils.isNotEmpty(commissionLogs)) {
				logger.info("commission:{},", JSON.toJSONString(commissionLogs));
				commissionLogMapper.insertSelectiveBatch(commissionLogs);
			}

			logger.info("加用户购买记录完成");
			int closeMinute = 6;
			TradeConfig config = configService.getTradeConfig(order.getCentreId());
			if (config != null) {
				Integer min = config.getAutoCloseNoPayOrderMin();
				if (min != null) {
					closeMinute = min;
				}
			}
			quartzManager.addJob(order.getOrdersn(), "ORDER", closeMinute, OrderNoPyJob.class, order.getId());
			logger.info("执行完成");
		} catch (Exception e) {
			logger.error("订单商品创建失败", e);
			throw new BDException(BusinessCode.ORDER_INFO_ISNULL);
		}
	}

    @Override
    public void sendTeamBegin(Order order, MarketingGroup marketingGroup) {
        //得到站点
        Centre centre = centreService.getByKey(order.getCentreId());
        PlatformConfig platformConfig = configService.getConfigByKey(ConfigKey.TEMPLATE_CONFIG.name(), centre.getCentreId());
        if (platformConfig == null) {
            throw new BDException("站点还未保存基础配置！");
        }
        TemplateConfig templateConfig = JSON.parseObject(platformConfig.getConfigValue(), TemplateConfig.class, Feature.OrderedField);

        String accessToken = getCentreAccessToken(centre);
        if (StringUtils.isEmpty(accessToken)) {
            throw new BDException("获取accessToken失败");
        }

        //得到用户信息
        Member mem = memberService.getByKey(order.getMid());
        if (mem == null) {
            logger.info("用户不存在！");
        }

        Template template = new Template();
        List<TemplateParam> paras = new ArrayList<>();

        InformationTemplate informationTemplate = null;
        if (templateConfig != null) {
            if (ValidateUtil.isNotEmptyString(templateConfig.getTeamBeginId())) {
                informationTemplate = informationTemplateService.findDetail(Long.parseLong(templateConfig.getTeamBeginId()));
            }
        }

        List<OrderProduct> list = orderProductMapper.getByOrderId(order.getId());
        String productName = list.get(0).getProductName();//商品名

        //发送开团提醒
        //模板id
        if (informationTemplate != null && ValidateUtil.isNotEmptyString(templateConfig.getWxTeamBeginId()) && ValidateUtil.isNotEmptyObjectOrString(mem.getAppOpenid())) {
            logger.info("----------------订阅消息构建开始----------------");
            //模板消息
            HashMap<String, Object> result = JSON.parseObject(informationTemplate.getTemplateValue(), LinkedHashMap.class, Feature.OrderedField);
            HashMap<String, Object> resultEntity = JSON.parseObject(informationTemplate.getTemplateEntity(), LinkedHashMap.class, Feature.OrderedField);
            if (result == null) {
                throw new BDException("订阅模板参数不存在！");
            } else {
                logger.info("----------------订阅消息模版参数构建开始----------------");
                Map<String, String> map = new HashMap<>();
                map.put("teamCount", String.valueOf(marketingGroup.getNeedJoinGroupNum()));
                map.put("payPrice", String.valueOf(order.getPayprice()));
                map.put("teamTime",
                        DateUtil.convertDateToStr(order.getPayTime() == null ? new Date() : order.getPayTime(), DateUtil.yyyy_MM_dd_HH_mm_ss));
                map.put("productName", productName);
                //发送消息参数 0
                // 1. 通过Map.keySet遍历key和value：
                for (String key : result.keySet()) {
                    paras.add(new TemplateParam(result.get(key).toString(), map.get(resultEntity.get(key).toString())));
                }

                template.setTemplateId(templateConfig.getWxTeamBeginId());
                template.setTouser(mem.getAppOpenid());
                template.setPage("pages/index/index");

                template.setTemplateParamList(paras);
                logger.info("-------------------------------------------------------templateParam" + template.toJSON());
            }
        } else {
            logger.info("拼团订阅消息配置错误！");
        }
    }

    @Override
    public void sendGZHTeamSucceed(Long centreId, Long mid, Map<String, String> map, String url) {
        logger.info("拼团成功centreId====" + centreId);
        logger.info("拼团成功mid====" + mid);
        PlatformConfig platformConfig = configService.getConfigByKey(ConfigKey.GZHTEMPLATE_CONFIG.name(), centreId);
        TemplateGZHConfig templateGZHConfig = null;
        if (platformConfig == null) {
            logger.info("该商户并未配置公众号模板====null");
            ;
        } else {
            templateGZHConfig = JSON.parseObject(platformConfig.getConfigValue(), TemplateGZHConfig.class, Feature.OrderedField);
        }
        //得到用户信息
        Member mem = memberService.getByKey(mid);
        if (mem == null) {
            logger.info("用户不存在！");
        }
        WxNotifyParam notifyParam = new WxNotifyParam();
        List<TemplateParam> paras = new ArrayList<>();
        InformationGZHTemplate informationGZHTemplate = null;


        //以下为特殊部分
        if (templateGZHConfig != null) {
            if (ValidateUtil.isNotEmptyString(templateGZHConfig.getTeamSucceedIdGZH())) {
                informationGZHTemplate = informationGZHTemplateService.findDetail(Long.parseLong(templateGZHConfig.getTeamSucceedIdGZH()));
            }
        }
        logger.info("拼团成功模版消息templateGZHConfig====" + JSONObject.toJSONString(templateGZHConfig));
        logger.info("拼团成功模版消息informationGZHTemplate====" + JSONObject.toJSONString(informationGZHTemplate));
        //模板id
        Member member = memberMapper.selectByPrimaryKey(mid);
        if (informationGZHTemplate != null && ValidateUtil.isNotEmptyString(templateGZHConfig.getWxTeamSucceedIdGZH()) && ValidateUtil.isNotEmptyObjectOrString(member.getOpenid())) {
            //模板消息
            HashMap<String, Object> result = JSON.parseObject(informationGZHTemplate.getTemplateValue(), LinkedHashMap.class, Feature.OrderedField);
            HashMap<String, Object> resultEntity = JSON.parseObject(informationGZHTemplate.getTemplateEntity(), LinkedHashMap.class, Feature.OrderedField);
            if (result == null) {
                throw new BDException("公众号消息模板参数不存在！");
            } else {
				/*
				通过Map.keySet遍历key和value：
				逻辑解释:
				map里存储的是供选择使用的键值对,
				paras里存的是模板需要的键值对,
				paras的key,为微信服务平台提供的代替换字段名,value为字段名对应的具体值(实体属性)
				 */
                for (String key : result.keySet()) {
                    paras.add(new TemplateParam(result.get(key).toString(), map.get(resultEntity.get(key).toString())));
                }

                //三个参数:类型 商户id 链接
                notifyParam.setMessageType(WxMessageType.MESSAGE_TYPE_TEMPLATE.getType());//模板消息
                notifyParam.setCenterId(centreId);
                notifyParam.setUrl(url);
                //三个参数:模板id 公众号端 会员openid
                notifyParam.setTemplateId(templateGZHConfig.getWxTeamSucceedIdGZH());
                notifyParam.setTeminal(WxTerminal.TERMINAL_GZH.getTerminal());
                notifyParam.setGzhOpenId(member.getOpenid());

                //内容字段
                Map<String, String> notifyParamItems = new HashMap<>();
                for (TemplateParam templateParam : paras) {
                    notifyParamItems.put(templateParam.getKey(), templateParam.getValue());
                }
                notifyParam.setItems(notifyParamItems);
                wxNotifyService.sendNotify(notifyParam);
            }
        } else {
            logger.info("公众号消息配置错误！");
        }
    }

    @Override
    public void sendTeamAwait(Order order, MarketingGroup marketingGroup, int count) {
        //得到站点
        Centre centre = centreService.getByKey(order.getCentreId());
        PlatformConfig platformConfig = configService.getConfigByKey(ConfigKey.TEMPLATE_CONFIG.name(), centre.getCentreId());
        if (platformConfig == null) {
            throw new BDException("站点还未保存基础配置！");
        }
        TemplateConfig templateConfig = JSON.parseObject(platformConfig.getConfigValue(), TemplateConfig.class, Feature.OrderedField);

        String accessToken = getCentreAccessToken(centre);
        if (StringUtils.isEmpty(accessToken)) {
            throw new BDException("获取accessToken失败");
        }

        //得到用户信息
        Member mem = memberService.getByKey(order.getMid());
        if (mem == null) {
            logger.info("用户不存在！");
        }

        Template template = new Template();
        List<TemplateParam> paras = new ArrayList<>();

        InformationTemplate informationTemplate = null;
        if (templateConfig != null) {
            if (ValidateUtil.isNotEmptyString(templateConfig.getTeamAwaitId())) {
                informationTemplate = informationTemplateService.findDetail(Long.parseLong(templateConfig.getTeamAwaitId()));
            }
        }

        List<OrderProduct> list = orderProductMapper.getByOrderId(order.getId());
        String productName = list.get(0).getProductName();//商品名

        //发送等待成团提醒
        //模板id
        if (informationTemplate != null && ValidateUtil.isNotEmptyString(templateConfig.getWxTeamAwaitId()) && ValidateUtil.isNotEmptyObjectOrString(mem.getAppOpenid())) {
            //模板消息
            HashMap<String, Object> result = JSON.parseObject(informationTemplate.getTemplateValue(), LinkedHashMap.class, Feature.OrderedField);
            HashMap<String, Object> resultEntity = JSON.parseObject(informationTemplate.getTemplateEntity(), LinkedHashMap.class, Feature.OrderedField);
            if (result == null) {
                throw new BDException("订阅模板参数不存在！");
            } else {
                Map<String, String> map = new HashMap<>();
                map.put("productName", productName);

                String endTime = DateUtil.convertDateToStr(marketingGroup.getEndTime() == null ? new Date() : marketingGroup.getEndTime(), DateUtil.yyyy_MM_dd_HH_mm_ss);
                map.put("teamCount", String.valueOf(marketingGroup.getNeedJoinGroupNum() - count));
                map.put("payPrice", String.valueOf(order.getPayprice()));
                map.put("teamTime", endTime);
                map.put("warmPrompt", "拼团时间截止至" + endTime + "!");

                String str = "";
                str += "拼团价 " + String.valueOf(order.getPayprice()) + "元,\n";
                str += "截止时间 " + endTime + ",\n";
                str += "剩余拼团人数 " + (String.valueOf(marketingGroup.getNeedJoinGroupNum() - count)) + ".\n";
                map.put("remark", str);
                //发送消息参数 0
                // 1. 通过Map.keySet遍历key和value：
                for (String key : result.keySet()) {
                    paras.add(new TemplateParam(result.get(key).toString(), map.get(resultEntity.get(key).toString())));
                }

                template.setTemplateId(templateConfig.getWxTeamAwaitId());
                template.setTouser(mem.getAppOpenid());
                template.setPage("pages/index/index");

                template.setTemplateParamList(paras);

            }
        } else {
            logger.info("拼团订阅消息配置错误！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cancelOrder(Long orderId, Integer flag) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null) {
            logger.info("cancel order error, not found order by id:{}", orderId);
            return 0;
        }
        //先得到人数
        Integer peoplenum = order.getPeoplenum();

        if (order.getPromoter() != null &&
                order.getSpellgroupStu() != 1 && order.getSgorderId() != null && order.getPaystatus() == 2) {
            throw new BDException(BusinessCode.ORDER_SPELLGROUP_ERROR);
        }

        Integer status = order.getStatus();
        //待付款、待发货的订单可取消订单(对应status为0,1)
        if (OrderStatus.wait_pay.getCode() != status && OrderStatus.wait_send.getCode() != status) {
            throw new BDException(BusinessCode.ORDER_CANCEL_ERROR);
        }

        Date now = new Date();
        List<OrderProduct> list = orderProductMapper.getByOrderId(orderId);
        List<OrderProduct> list1 = new ArrayList();
        for (OrderProduct item : list) {
            Date timeEnd = item.getTimeend();
            if (timeEnd != null && timeEnd.before(now)
                    && order.getPromoter() == null) {
                //已截团
                throw new BDException(BusinessCode.ORDER_CANCEL_OVERTIME);
            }
            if (item.getStatus() != -1) {
                list1.add(item);
            }

        }

        OrderProduct op = new OrderProduct();
        op.setStatus(OrderStatus.cancel.getCode());
        op.setCancelTime(new Date());
        Double refundPrice = 0.00;

        if (OrderStatus.wait_send.getCode() == order.getStatus() && !MarketingGroupRulesEnum.MISS.getCode().equals(order.getGroupRules())) {
            order.setRefundTime(new Date());
            op.setPayStatus(PayStatus.REFUND_SUCCESS.getCode());
            if (order.getPromoter() != null && flag != null
                    && flag == 1) {
                op.setSpellgroupStu(3);
            } else if (order.getPromoter() != null) {
                op.setSpellgroupStu(4);
            }
            Integer payType = order.getPaytype();

            Double applyPrice = 0.00;
            //取消订单数
            int cancelNum = orderProductMapper.countCancelByOrderId(order.getId());
            if (order.getTrId() != null && cancelNum > 0) {
                //比例
                BigDecimal proportion = new BigDecimal("0");
                //未扣优惠卷价格
                String countMoney = orderProductMapper.sumOrdProductById(order.getId());
                //得到比例四舍五入保留4位小数
                proportion = (order.getPayprice().divide(new BigDecimal(countMoney), 4, BigDecimal.ROUND_HALF_UP)).setScale(4, BigDecimal.ROUND_HALF_UP);
                //单品取消总金额
                Double price = Double.parseDouble("0");
                //得到单品取消的订单商品Id数据集合
                List<OrderProduct> productIds = orderProductMapper.getOrderProdctId(order.getId());
                if (productIds.size() > 0) {
                    for (OrderProduct ordProduct : productIds) {
                        OrderProduct orderProduct = orderProductMapper.selectByPrimaryKey(ordProduct.getId());
                        //最终比例价格 商品总价乘以汇率保留四位小数四舍五入
                        price = price + ((orderProduct.getPrice().multiply(proportion)).setScale(4, BigDecimal.ROUND_HALF_UP)).doubleValue();
                    }
                }
                //退款金額為支付金額減掉之前單品取消的金額四舍五入
                applyPrice = order.getPayprice().subtract(new BigDecimal(price)).doubleValue();
            } else {
                //用了优惠卷没有单品取消的
                if (order.getPayprice() != null && order.getTrId() != null) {
                    applyPrice = order.getPayprice().doubleValue();
                } else {
                    //没用优惠卷
                    applyPrice = orderProductMapper.getNormalPriceByOrderId(orderId);
                }
            }
            ////////////////////////////////////////////////////////积分退还////////////////////////////////////////////START///////////////////
            if (cancelNum > 0 && order.getDeductcredit() > 0 && order.getDeductprice().doubleValue() > 0 && order.getTrId() == null) {
                BigDecimal proportion = new BigDecimal("0");
                String countMoney = orderProductMapper.sumOrdProductById(order.getId());
                proportion = (order.getPayprice().divide(new BigDecimal(countMoney), 4, BigDecimal.ROUND_HALF_UP)).setScale(4, BigDecimal.ROUND_HALF_UP);
                Double price = Double.parseDouble("0");
                List<OrderProduct> productIds = orderProductMapper.getOrderProdctId(order.getId());
                if (productIds.size() > 0) {
                    for (OrderProduct ordProduct : productIds) {
                        OrderProduct orderProduct = orderProductMapper.selectByPrimaryKey(ordProduct.getId());
                        price = price + ((orderProduct.getPrice().multiply(proportion)).setScale(4, BigDecimal.ROUND_HALF_UP)).doubleValue();
                    }
                }
                applyPrice = order.getPayprice().subtract(new BigDecimal(price)).doubleValue();
            } else if (order.getTrId() == null && cancelNum == 0 && order.getDeductprice().doubleValue() > 0) {
                applyPrice = order.getPayprice().doubleValue();
            }
            //只要取消订单就退还所有积分
            integralService.returnIntegralNew(order, order.getDeductcredit());
            ////////////////////////////////////////////////////////积分退还////////////////////////////////////////////END///////////////////
            if (applyPrice == 0 && order.getPayprice().doubleValue() != 0) {
                logger.info("applyPrice is 0", applyPrice, order.getId());
                return 0;
            }
            logger.info("申请退款订单类型：" + payType);
            if (PayType.WX_PAY.equals(payType) || PayType.WX_APP_PAY.equals(payType)) {
                if (StringUtils.isEmpty(order.getPayno())) {
                    throw new BDException(BusinessCode.ORDER_STATUS_ERROR);
                }
                String refundNo = order.getOrdersn().concat("R");
                try {
                    logger.info("申请退款金额:{},payNo:{}", applyPrice, order.getPayno());
                    Payment payment = new Payment();
                    List<Order> orders = orderMapper.selectOrderByOutTradeNo(order.getOutTradeNo());
                    BigDecimal totalPrice = new BigDecimal("0");
                    String refundsn = null;
                    for (Order order1 : orders) {
                        totalPrice = totalPrice.add(order1.getPayprice());
                        if (order1.getStatus() == -1 && StringUtils.isNotBlank(order1.getRefundsn())) {
                            refundsn = orders.get(orders.size() - 1).getRefundsn();

                        }
                    }

                   if (StringUtils.isNotEmpty(order.getChanelcode()) && order.getChanelcode().equals(PayChannelEnum.YPL.getCode()) && applyPrice > 0.01) {
                        logger.info("进来易票联退款");
                        //商户用户
                        Centre centre = null;

                        if (order.getCentreId() != null && order.getCentreId() > 0) {
                            centre = centreService.getCentreById(order.getCentreId());
                        }

                        if (refundsn == null) {
                            String sn = DateUtils.format(new Date(), "ddHHmmss");
                            refundNo = "REFUND".concat(sn);
                        }

                        try {
                            String notifyUrl = templatemsgCreateUserUrl + "/notify/yfz/refundNotify";// 退款结果通知
                            YFZPayutil.refundApply(order.getPayprice(), order.getOutTradeNo(), centre, refundNo, notifyUrl, null);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        order.setRefundNo(refundNo);
                        payment.setPayTradeNo(refundNo);
                    } else {
						//商户开的小程序
						WxPayRefundResult refund = myWxpayService.refund(order.getPayno(), null, refundNo, totalPrice.doubleValue(), applyPrice);
						logger.info("微信退款返回数据---" + JSONObject.toJSONString(refund));
                        if (refund == null) {
                            logger.info("apply wx refund cant't get result!");
                            return 0;
                        }
                        order.setRefundsn(refund.getOutTradeNo());
                        order.setRefundNo(refund.getRefundId());
                        payment.setPayTradeNo(refund.getRefundId());
                        logger.info("refundNo:{},refundId:{}", refund.getOutRefundNo(), refund.getRefundId());

                    }

                    payment.setOutTradeNo(order.getOutTradeNo());
                    payment.setOutRefundNo(refundNo);
                    payment.setMoney(order.getPayprice());
                    payment.setStatus(2);
                    payment.setType("2");
                    payment.setStyle(4);
                    payment.setMid(order.getMid());
                    payment.setTuikuantime(order.getRefundTime());
                    payment.setOutRefundNo(refundNo);
                    payment.setTuikuanstatus(1);
                    payment.setUpdateTime(new Date());
                    paymentService.savePayment(payment);
                } catch (Exception e) {
                    logger.info("wx refund error:{}", e.getMessage());
                    return 0;
                }
            } else if (PayType.BALANCE_PAY.equals(payType)) {
                balanceService.recharge(order.getMid(), applyPrice.doubleValue(),
                        BalanceLogStyle.ORDER_REFUND.getCode(), RechargeType.ORDER_REFUND.getType(), order.getOrdersn());
            }  else {
                //TODO:支付通道
            }

            refundPrice = applyPrice;
        }
        if (order.getTrId() != null) {
            //退还优惠券
            ticketService.updateRecordToNoUse(order.getTrId());
        }
        OrderProductExample ope = new OrderProductExample();
        ope.or().andOrderidEqualTo(orderId);
        orderProductMapper.updateByExampleSelective(op, ope);

        order.setStatus(OrderStatus.cancel.getCode());
        order.setRemark("用户主动取消订单");
        //拼团订单
        if (order.getPromoter() != null && flag != null
                && flag == 1) {
            order.setSpellgroupStu(3);
        } else if (order.getPromoter() != null) {
            order.setSpellgroupStu(4);
            if (status != 0) {
                SpellGroupOrdVo vo = new SpellGroupOrdVo();
                vo.setOrderid(order.getSgorderId());
                vo.setPeoplenum(1);
                //拼团人数减1
                int num = orderMapper.changePeoplenum(vo);
                if (num < 0) {
                    logger.info("拼团数没有修改成功");
                    return 0;
                } else {
                    order.setPeoplenum(null);
                }
            }
        }
        int r = orderMapper.updateByPrimaryKeySelective(order);
        OrderProduct record = new OrderProduct();
        record.setOrderid(order.getId());
        record.setStatus(OrderStatus.cancel.getCode());
        orderProductMapper.updateByParam(record);

        if (r > 0) {
            //库存回退
            this.refundProductsStock(list1, order.getOrderType());
            //是购买版本订单
            if (order.getIsCentreord() == 1) {
                //删除未付款自动关闭商户的信息
                centreMapper.delByMidAndStu(order.getMid());
            }
        }
        //拼团订单是发起人是自己
        if (order.getPromoter() != null &&
                //order.getPromoter().longValue() == order.getMid().longValue() &&
                order.getPaystatus() == 2 && flag == null && order.getId().equals(order.getSgorderId())) {
            logger.info("拼团发起人取消订单从新分配发起人");
            SpellGroupOrdVo vo = new SpellGroupOrdVo();
            vo.setSpellgroupStu(1);//拼团中
            vo.setSgorderId(order.getSgorderId());//发起人拼团订单
            vo.setOrderid(order.getSgorderId());//订单号不等于发起人拼团订单的
            //拼团订单
            List<SpellGroupOrdVo> orders = orderMapper.getSpellGroupOrdByStu(vo);
            if (CollectionUtils.isNotEmpty(orders)) {
                //修改发起人
                SpellGroupOrdVo vo2 = new SpellGroupOrdVo();
                vo2.setSpellgroupStu(1);//拼团中
                vo2.setSgorderId(order.getSgorderId());//发起人拼团订单
                vo2.setOrderid(order.getSgorderId());//订单号不等于发起人拼团订单的
                vo2.setMid(orders.get(0).getMid());//发起人id
                if (peoplenum - 1 >= 0) {
                    vo2.setPeoplenum(peoplenum - 1);//拼团成功人数为键1
                }
                vo2.setNewSgorderId(orders.get(0).getOrderid());//发起人拼团订单号
                //发起人取消订单重新修改拼团发起人
                orderMapper.updateSpellGroupOrdByStu(vo2);
            }
        }
        Member member = memberService.getByKey(order.getMid());
        //发送退款公众号通知
        if (member != null && ValidateUtil.isNotEmptyString(member.getOpenid())) {
            String firstString = "您好，您的订单 " + order.getOrdersn() + " 交易未成功，已退款!";
            Map<String, String> map = new HashMap<>();
            String url =  templatemsgCreateUserUrl + "/bdsh/"+member.getCentreId()+"/index.html";
            map.put("firstString", firstString);
            map.put("refundReason", "订单取消");
            map.put("refundPrice", new BigDecimal(refundPrice).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
            map.put("remarkrest", "点击页面查看详情");
            sendGZHRefund(order.getCentreId(), order.getMid(), map, url);
        }

        //只要取消订单就将相关分佣置为无效
        commissionService.updateCommissionByOrderId(order.getId());


        return r;
    }


    @Override
    public void sendGZHRefund(Long centreId, Long mid, Map<String, String> map, String url) {
        PlatformConfig platformConfig = configService.getConfigByKey(ConfigKey.GZHTEMPLATE_CONFIG.name(), centreId);
        TemplateGZHConfig templateGZHConfig = null;
        if (platformConfig == null) {
            logger.info("该商户并未配置公众号模板====null");
            ;
        } else {
            templateGZHConfig = JSON.parseObject(platformConfig.getConfigValue(), TemplateGZHConfig.class, Feature.OrderedField);
        }
        //得到用户信息
        Member mem = memberService.getByKey(mid);
        if (mem == null) {
            logger.info("用户不存在！");
        }
        WxNotifyParam notifyParam = new WxNotifyParam();
        List<TemplateParam> paras = new ArrayList<>();
        InformationGZHTemplate informationGZHTemplate = null;


        //以下为特殊部分
        if (templateGZHConfig != null) {
            if (ValidateUtil.isNotEmptyString(templateGZHConfig.getRefundIdGZH())) {
                informationGZHTemplate = informationGZHTemplateService.findDetail(Long.parseLong(templateGZHConfig.getRefundIdGZH()));
            }
        }
        //模板id
        Member member = memberMapper.selectByPrimaryKey(mid);
        if (informationGZHTemplate != null && ValidateUtil.isNotEmptyString(templateGZHConfig.getWxRefundIdGZH()) && ValidateUtil.isNotEmptyObjectOrString(member.getOpenid())) {
            //模板消息
            HashMap<String, Object> result = JSON.parseObject(informationGZHTemplate.getTemplateValue(), LinkedHashMap.class, Feature.OrderedField);
            HashMap<String, Object> resultEntity = JSON.parseObject(informationGZHTemplate.getTemplateEntity(), LinkedHashMap.class, Feature.OrderedField);
            if (result == null) {
                throw new BDException("公众号消息模板参数不存在！");
            } else {
				/*
				通过Map.keySet遍历key和value：
				逻辑解释:
				map里存储的是供选择使用的键值对,
				paras里存的是模板需要的键值对,
				paras的key,为微信服务平台提供的代替换字段名,value为字段名对应的具体值(实体属性)
				 */
                for (String key : result.keySet()) {
                    paras.add(new TemplateParam(result.get(key).toString(), map.get(resultEntity.get(key).toString())));
                }

                //三个参数:类型 商户id 链接
                notifyParam.setMessageType(WxMessageType.MESSAGE_TYPE_TEMPLATE.getType());//模板消息
                notifyParam.setCenterId(centreId);
                notifyParam.setUrl(url);
                //三个参数:模板id 公众号端 会员openid
                notifyParam.setTemplateId(templateGZHConfig.getWxRefundIdGZH());
                notifyParam.setTeminal(WxTerminal.TERMINAL_GZH.getTerminal());
                notifyParam.setGzhOpenId(member.getOpenid());

                //内容字段
                Map<String, String> notifyParamItems = new HashMap<>();
                for (TemplateParam templateParam : paras) {
                    notifyParamItems.put(templateParam.getKey(), templateParam.getValue());
                }
                notifyParam.setItems(notifyParamItems);
                wxNotifyService.sendNotify(notifyParam);
            }
        } else {
            logger.info("公众号消息配置错误！");
        }
    }


	@Override
	public void sendGZHTeamFailed(Long centreId, Long mid, Map<String, String> map, String url) {
		PlatformConfig platformConfig = configService.getConfigByKey(ConfigKey.GZHTEMPLATE_CONFIG.name(), centreId);
		TemplateGZHConfig templateGZHConfig = null;
		if (platformConfig == null) {
			logger.info("该商户并未配置公众号模板====null");

		} else {
			templateGZHConfig = JSON.parseObject(platformConfig.getConfigValue(), TemplateGZHConfig.class, Feature.OrderedField);
		}
		//得到用户信息
		Member mem = memberService.getByKey(mid);
		if (mem == null) {
			logger.info("用户不存在！");
		}
		WxNotifyParam notifyParam = new WxNotifyParam();
		List<TemplateParam> paras = new ArrayList<>();
		InformationGZHTemplate informationGZHTemplate = null;


		//以下为特殊部分
		if (templateGZHConfig != null) {
			if (ValidateUtil.isNotEmptyString(templateGZHConfig.getTeamFailIdGZH())) {
				informationGZHTemplate = informationGZHTemplateService.findDetail(Long.parseLong(templateGZHConfig.getTeamFailIdGZH()));
			}
		}
		//模板id
		Member member = memberMapper.selectByPrimaryKey(mid);
		if (informationGZHTemplate != null && ValidateUtil.isNotEmptyString(templateGZHConfig.getWxTeamFailIdGZH()) && ValidateUtil.isNotEmptyObjectOrString(member.getOpenid())) {
			//模板消息
			HashMap<String, Object> result = JSON.parseObject(informationGZHTemplate.getTemplateValue(), LinkedHashMap.class, Feature.OrderedField);
			HashMap<String, Object> resultEntity = JSON.parseObject(informationGZHTemplate.getTemplateEntity(), LinkedHashMap.class, Feature.OrderedField);
			if (result == null) {
				throw new BDException("公众号消息模板参数不存在！");
			} else {
				/*
				通过Map.keySet遍历key和value：
				逻辑解释:
				map里存储的是供选择使用的键值对,
				paras里存的是模板需要的键值对,
				paras的key,为微信服务平台提供的代替换字段名,value为字段名对应的具体值(实体属性)
				 */
				for (String key : result.keySet()) {
					paras.add(new TemplateParam(result.get(key).toString(), map.get(resultEntity.get(key).toString())));
				}

				//三个参数:类型 商户id 链接
				notifyParam.setMessageType(WxMessageType.MESSAGE_TYPE_TEMPLATE.getType());//模板消息
				notifyParam.setCenterId(centreId);
				notifyParam.setUrl(url);
				//三个参数:模板id 公众号端 会员openid
				notifyParam.setTemplateId(templateGZHConfig.getWxTeamFailIdGZH());
				notifyParam.setTeminal(WxTerminal.TERMINAL_GZH.getTerminal());
				notifyParam.setGzhOpenId(member.getOpenid());

				//内容字段
				Map<String, String> notifyParamItems = new HashMap<>();
				for (TemplateParam templateParam : paras) {
					notifyParamItems.put(templateParam.getKey(),  templateParam.getValue());
				}
				notifyParam.setItems(notifyParamItems);
				wxNotifyService.sendNotify(notifyParam);
			}
		} else {
			logger.info("公众号消息配置错误！");
		}
	}

	@Override
	public int updOrderPayAttach(Map<String, Object> updMap) {
		return orderMapper.updOrderPayAttach(updMap);
	}

	@Override
	public void updateOpenid(Order order1) {
		orderMapper.updateOpenid(order1);
	}

	@Override
	public List<Map<String, Object>> getStatusCounts(Long mid) {
		List<Map<String, Object>> list = orderMapper.getStatusCounts(mid);
		for (Map<String, Object> item : list) {
			if (item == null) {
				continue;
			}
			item.put("statusName", OrderStatus.get((Integer) item.get("status")));
		}
		return list;
	}

	@Override
	public List<Map<String, Object>> getCanyinOrderCounts(Long mid) {
		return orderMapper.getCanyinOrderCounts(mid);
	}

	/**
	 * 校验库存，封装订单商品对象,创建订单,发送消息
	 *
	 * @param member
	 * @param products
	 * @param sname
	 * @param mobile
	 * @param houseNo
	 * @param couponId
	 * @param address
	 * @return
	 */
	private String newCheckStockMarketing(Member member, List<MemberCartVo> products, String sname, String mobile, String houseNo, List list, Long couponId,
										  String address, String alldweight, String dispatchid, String dispatchprice, String iscomment,
										  Integer isSpellgroup, Long orderId, Long promoter, String appointmentName, String appointmentMobile,
										  Date appointmentDate, String seatNum, Integer cateringType, Integer dispatchtype, Long clerkId,
										  Integer orderType, Integer isSubimtOrgType, Long addressId, Long activityId, Integer groupRules
			, Integer marketingGroupType, Integer portType, Long shareMid, List<UsableTeamMiddle> usableTeamMiddleList) throws ParseException {


		Member teamLeader = null;


		Address deliveryAddress = null;
		if (addressId != null) {
			deliveryAddress = addressService.getByKey(addressId);
		}

		List<Centre> centres = centreService.listAllCentres();
		if (CollectionUtils.isEmpty(centres)) {
			logger.info("not found centre info! auto check order delivery end...");
			return null;
		}

		String payNo = null;
		String resOrderId = null;
		for (Centre centre : centres) {
			List<MemberCartVo> collect = products.stream().filter(MemberCartVo -> MemberCartVo.getCentreId().toString().equals(centre.getCentreId().toString())).collect(
					Collectors.toList());
			if (CollectionUtils.isEmpty(collect)) {
				continue;
			}
			Order order = new Order();
			BigDecimal orderPrice = new BigDecimal(0d);
			BigDecimal goodsPrice = new BigDecimal(0d);
			BigDecimal payPrice = new BigDecimal(0d);
			Integer goodstotal = 0;
			BigDecimal headcommission = new BigDecimal(0d);
			BigDecimal allweight = new BigDecimal(0d);
			//用户推荐人佣金
			BigDecimal usercommission = new BigDecimal(0d);
			//用户推荐人上级佣金
			BigDecimal superusercommission = new BigDecimal(0d);
			Long centreId = null;
			String orderSn = OrderSnUtil.getSn("D");
			if (payNo == null) {
				String sn = DateUtils.format(new Date(), "mmss");
				payNo = "X_OC_".concat(orderSn).concat("_").concat(sn);
			}
			List<OrderProduct> ops = new ArrayList<>();
			List<ProductCentre> productCentreList = new ArrayList<>();
			Map<String, String> skuMap = new HashMap<>(16);
			//版本推荐人
			Member referralsMenber = null;

			for (MemberCartVo mc : collect) {

				boolean giftBagFlag = false;
				if (isSubimtOrgType == 2 && ProductType.Spellgroup.getType() == orderType && MarketingGroupTypeEnum.GIFT_BAG.getCode().equals(marketingGroupType)) {
					giftBagFlag = true;
				}

				Long centreProductId = mc.getProductId();
				ProductCentre pc = new ProductCentre();
				Activity activity = new Activity();
				if (giftBagFlag) {
					activity = activityMapper.selectByPrimaryKey(centreProductId);
					if (activity == null) {
						throw new BDException(BusinessCode.ORDER_PRODUCTS_ERROR);
					}
					if (null == teamLeader) {
						teamLeader = memberService.getByKey(activity.getTeamId());
					}
				} else {
					pc = productCentreService.getByKeyWithCache(centreProductId);
					if (pc == null) {
						throw new BDException(BusinessCode.ORDER_PRODUCTS_ERROR);
					}
					if (null == teamLeader) {
						teamLeader = memberService.getByKey(pc.getLiansuoid());
					}
				}

				if (!giftBagFlag) {
					productCentreList.add(pc);
					skuMap.put(pc.getId().toString(), mc.getSpecs());
					if (pc.getMaxbuy() > 0 && pc.getMaxbuy() < mc.getTotal()) {
						throw new BDException(BusinessCode.BUY_MAX_TOO_MANY);
					}
					centreId = pc.getCentreId();
					int t = orderProductMapper.countMidProductNums(member.getId(), centreProductId);
					if (pc.getUsermaxbuy() > 0 && pc.getUsermaxbuy() <= t) {
						throw new BDException(BusinessCode.BUY_MAX_LG_TOO_MANY);
					}
					if (pc.getIsKuaidi() == 1 && StringUtils.isBlank(address) && ValidateUtil.isEmptyString(mobile)) {
						throw new BDException(BusinessCode.ORDER_MOBILE_ISNULL);
					}
				}

				ProductSkuCentre skuCentre = null;
				OrderProduct op = new OrderProduct();
				//活动ID
				op.setActivityId(activityId);
				Long centreSkuId = mc.getSkuId();
				if (!giftBagFlag && pc.getHasoption() != null && pc.getHasoption() == 1) {
					//有SKU
					if (mc.getSkuId() == null) {
						skuCentre = productCentreService.getSkuBySpecs(mc.getSpecs());
						centreSkuId = skuCentre.getId();
						if (null == skuCentre) {
							throw new BDException(BusinessCode.ORDER_PRODUCT_SKU_ERROR);
						}
					} else {
						skuCentre = productCentreService.getSkuByKeyWithCache(mc.getSkuId());
					}

					if (skuCentre == null) {
						throw new BDException(BusinessCode.ORDER_PRODUCT_SKU_ERROR);
					}
				}
				op.setSkuId(centreSkuId);

				//校验商品库存
				Long platformProductId = pc.getProductId();
				Map<String, String> map = new HashMap<>();
				Integer total = mc.getTotal();
				if (platformProductId != null && platformProductId > 0) {
				} else {
					boolean hasOption = pc.getHasoption() != null && pc.getHasoption() == 1;
					if (isSubimtOrgType != null && (isSubimtOrgType == 1 || isSubimtOrgType == 2)) {
						marketingSeckillService.checkStockAndTime(activityId, isSubimtOrgType, mc, orderId);
					}

					if (isSubimtOrgType == 2) {
						//查询大礼包中包含的优惠券是否充足
						if(activity.getId() != null){
							ticketService.giftPacksTickets(activity.getId());
						}

						//校验优惠券是否有库存
						ticketService.groupTickets(activityId);

						order.setGroupRules(groupRules);

						MarketingGroup marketingGroup = marketingGroupService.getMarketingGroupById(activityId);
						order.setMarketingGroupType(marketingGroup.getMarketingGroupType());
						//活动销售量增加
						String activitySaleKey = String.format(RedisKey.GROUP_ACTIVITY_SALES_KEY_CACHE, activityId);
						long sSale = localRedis.increamNum(activitySaleKey, total);
						if (marketingGroup.getStock() < total) {
							localRedis.increamNum(activitySaleKey, -total);
							throw new BDException((giftBagFlag ? activity.getActivityName() : pc.getTitle()).concat("已卖完,请删除该商品"));
						}
						map.put(RedisKey.GROUP_ACTIVITY_SALES_KEY_CACHE, activitySaleKey);
						map.put(RedisKey.GROUP_ACTIVITY_SALES_TOTAL_CACHE, total.toString());

						if (hasOption) {
							MarketingGroupSku marketingGroupSku = marketingGroupService.getSkuBySkuId(activityId, centreSkuId);
							//多规格的活动商品销售量增加
							String activitySkuSaleKey = String.format(RedisKey.SECKILL_ACTIVITY_SALES_SKU_KEY_CACHE, activityId, centreSkuId);
							long skuSale = localRedis.increamNum(activitySkuSaleKey, total);
							if (marketingGroupSku.getStock() < total) {
								localRedis.increamNum(activitySkuSaleKey, -total);
								throw new BDException((giftBagFlag ? activity.getActivityName() : pc.getTitle()).concat("已卖完,请删除该商品"));
							}
							map.put(RedisKey.SECKILL_ACTIVITY_SALES_SKU_KEY_CACHE, activitySkuSaleKey);
							map.put(RedisKey.SECKILL_ACTIVITY_SALES_SKU_TOTAL_CACHE, total.toString());
						}
					} else {
						//商户自卖商品
						if (hasOption) {
							//有SKU
							op.setSkuId(centreSkuId);
							long sSale = localRedis.increamNum(CACHE_KEY_PRODUCT_CENTRE_SKU_SALE.concat(String.valueOf(centreSkuId)), total);
							if (skuCentre.getStock() < sSale) {
								localRedis.increamNum(CACHE_KEY_PRODUCT_CENTRE_SKU_SALE.concat(String.valueOf(centreSkuId)), -total);
								throw new BDException(pc.getTitle().concat("已卖完,请删除该商品"));
							}
							map.put("CACHE_KEY_PRODUCT_CENTRE_SKU_SALE", CACHE_KEY_PRODUCT_CENTRE_SKU_SALE.concat(String.valueOf(centreSkuId)));
							map.put("CACHE_KEY_PRODUCT_CENTRE_SKU_SALE_TOTAL", total.toString());
						}


						long sale = localRedis.increamNum(CACHE_KEY_PRODUCT_CENTRE_SALE.concat(String.valueOf(pc.getId())), total);
						if (pc.getTotal() <= sale) {
							ProductCentre productCentre = new ProductCentre();
							productCentre.setDisplayorder(0);
							productCentre.setId(pc.getId());
							//修改排序
							productCentreMapper.updateByPrimaryKeySelective(productCentre);
						}
						if (pc.getTotal() < sale) {
							localRedis.increamNum(CACHE_KEY_PRODUCT_CENTRE_SALE.concat(String.valueOf(pc.getId())), -total);
							throw new BDException(pc.getTitle().concat("已卖完,请删除该商品"));
						}
						map.put("CACHE_KEY_PRODUCT_CENTRE_SALE", CACHE_KEY_PRODUCT_CENTRE_SALE.concat(String.valueOf(pc.getId())));
						map.put("CACHE_KEY_PRODUCT_CENTRE_SALE_TOTAL", total.toString());
					}

				}
				list.add(map);
				op.setCartId(mc.getId());
				op.setMid(member.getId());
				op.setOpenid(member.getOpenid());
				op.setSname(sname);
				op.setMobile(mobile);
				op.setNickname(member.getNickname());
				op.setProductId(giftBagFlag ? activity.getId() : pc.getId());
				op.setIsLiansuo(giftBagFlag ? (activity.getTeamId() == null ? 0 : 1) : (pc.getLiansuoid() == null ? 0 : 1));
				op.setSelProductId(giftBagFlag ? null : pc.getProductId());
				op.setProductCode(giftBagFlag ? null : pc.getGoodscode());
				op.setTotal(mc.getTotal());
				op.setThumb(giftBagFlag ? activity.getThumb() : pc.getThumb());
				if (null != pc.getProductId() && pc.getProductId() > 0) {
					op.setBaseproductid(String.valueOf(pc.getProductId()));
				}
				BigDecimal marketPrice = giftBagFlag ? activity.getActivityPrice() : pc.getMarketprice();
				//vip商户数据集合
				List<String> strlist = Arrays.asList(member.getVipofcentreId().split("-"));
				//用户是这个商户的vip
				if (member.getIsVip() == 1 && strlist.indexOf(centre.getCentreId().toString()) != -1) {
					if (pc.getVipprice() != null && pc.getVipprice().doubleValue() > 0 && pc.getIsvip() == 1) {
						marketPrice = pc.getVipprice();
					}
				}
				op.setMarketprice(marketPrice);
				op.setCostprice(giftBagFlag ? null : pc.getCostprice());
				op.setProductprice(giftBagFlag ? activity.getActivityPrice() : pc.getProductprice());
				op.setWeight(giftBagFlag ? null : pc.getWeight().multiply(BigDecimal.valueOf(mc.getTotal())));
				op.setShortTitle(giftBagFlag ? activity.getActivityName() : pc.getShortTitle());
				op.setProductName(giftBagFlag ? activity.getActivityName() : pc.getTitle());
				op.setSpecTitle(giftBagFlag ? null : pc.getSpecTitle());
				op.setUnit(giftBagFlag ? null : pc.getUnit());
				op.setCredit(0);
				op.setIscredits(0);
				if (pc.getCredit() != null && pc.getCredit() > 0) {
					op.setCredit(new BigDecimal(pc.getCredit() * mc.getTotal()).intValue());
					op.setIscredits(1);
				}

				op.setIsKuaidi(mc.getIsKuaidi());
				op.setHeadtype(giftBagFlag ? null : pc.getHeadtype());
				op.setSuperiortype(giftBagFlag ? null : pc.getSuperiortype());
				op.setHeadcommission(giftBagFlag ? null : pc.getHeadcommission());

				op.setSuperiorcommission(giftBagFlag ? null : pc.getSuperiorcommission());
				op.setUsertype(giftBagFlag ? null : pc.getUsertype());
				op.setUsercommission(giftBagFlag ? null : pc.getUsercommission());
				op.setSuperusertype(giftBagFlag ? null : pc.getSuperusertype());
				op.setSuperusercommission(giftBagFlag ? null : pc.getSuperusercommission());
				//多规格商品
				if (pc.getHasoption() != null && pc.getHasoption() == 1) {
					op.setOptionname(skuCentre.getTitle());
					op.setHeadtype(skuCentre.getHeadtype());
					op.setSuperiortype(pc.getSuperiortype());
					op.setHeadcommission(pc.getHeadcommission());
					op.setSuperiorcommission(pc.getSuperiorcommission());
					//团购多规格产品价格计算
					if (ProductType.Spellgroup.getType() == orderType) {
						MarketingGroupSku marketingGroupSku = marketingGroupService.getSkuBySpecs(activityId, mc.getSpecs());
						if (null != marketingGroupSku) {
							if (member.getIsVip() == 1 && marketingGroupSku.getVipPrice() != null && marketingGroupSku.getVipPrice().compareTo(BigDecimal.ZERO) > 0) {
								op.setMarketprice(marketingGroupSku.getVipPrice());
							} else {
								op.setMarketprice(marketingGroupSku.getGroupPrice());
							}
						}
					}
					//普通多规格商品价格获取
					else {
						if (skuCentre.getMarketprice() != null) {
							op.setMarketprice(skuCentre.getMarketprice());
							if (member.getIsVip() == 1) {
								if (skuCentre.getVipprice() != null && skuCentre.getVipprice().doubleValue() > 0 && pc.getIsvip() == 1) {
									op.setMarketprice(skuCentre.getVipprice());
								}
							}
						}
					}
					if (skuCentre.getProductprice() != null) {
						op.setProductprice(skuCentre.getProductprice());
					}
					if (skuCentre.getWeight() != null) {
						op.setWeight(skuCentre.getWeight().multiply(BigDecimal.valueOf(mc.getTotal())));
					}
					if (skuCentre.getCostprice() != null && skuCentre.getCostprice().compareTo(BigDecimal.ZERO) == 1) {
						op.setCostprice(skuCentre.getCostprice());
					}
					if (StringUtils.isNotEmpty(skuCentre.getThumb())) {
						op.setThumb(skuCentre.getThumb());
					}
				}
				//拼团商品，重新计算拼团商品的价格
				else if (orderType == ProductType.Spellgroup.getType()) {
					MarketingGroup marketingGroup = marketingGroupService.getMarketingGroupById(activityId);
					if (member.getIsVip() == 1 && marketingGroup.getVipPrice() != null && marketingGroup.getVipPrice().compareTo(BigDecimal.ZERO) > 0) {
						op.setMarketprice(marketingGroup.getVipPrice());
					} else {
						op.setMarketprice(marketingGroup.getGroupPrice());
					}
				}

				//商品总价格=商品单价*商品数量，这里是实际支付的金额
				op.setPrice(op.getMarketprice().multiply(BigDecimal.valueOf(mc.getTotal())));
				if (pc.getIsKuaidi() != null && pc.getIsKuaidi() == 0) {
					op.setProvince(teamLeader.gettProvince());
					op.setCity(teamLeader.gettCity());
					op.setDistrict(teamLeader.gettArea());
					op.setAddress(teamLeader.gettShopname());
				} else {
					op.setProvince(member.getProvince());
					op.setCity(member.getCity());
					op.setDistrict(member.getArea());
					op.setAddress(member.getAddress());
				}

				op.setSaddress(op.getProvince() + op.getCity() + op.getDistrict() + op.getAddress());
				if (teamLeader != null) {
					op.settMid(teamLeader.getId());
					op.settNickname(teamLeader.getNickname());
					op.setTtMid(teamLeader.getUpTeamid());
					op.setTtNickname(teamLeader.getUpTeamname());
				}

				op.setCommision1(calcHeadCommission(op.getHeadtype(), op.getHeadcommission(), op.getPrice(), op.getTotal()));
				op.setCommision2(new BigDecimal(0));
				if (teamLeader != null && teamLeader.getUpTeamid() != null) {
					op.setCommision2(calcHeadCommission(op.getSuperiortype(), op.getSuperiorcommission(), op.getPrice(), op.getTotal()));
				}
				//用户推荐佣金
				op.setCommision5(new BigDecimal(0));
				//用户有推荐人
				if (member.getUserid() != null && pc.getUsertype() != null && pc.getUsercommission() != null) {
					op.setCommision5(calcHeadCommission(pc.getUsertype(),
							pc.getUsercommission(), op.getPrice(), op.getTotal()));
				}
				//用户推荐人上级佣金
				op.setCommision6(new BigDecimal(0));
				//用户有推荐人上级
				if (member.getUpUserid() != null && pc.getSuperusertype() != null && pc.getSuperusercommission() != null) {
					op.setCommision6(calcHeadCommission(pc.getSuperusertype(),
							pc.getSuperusercommission(), op.getPrice(), op.getTotal()));
				}
				//用户代理佣金
				op.setCommision7(new BigDecimal(0));
				op.setAccountManagerCommision(new BigDecimal(0));

				//商品分享佣金
				op.setProductShareCommision(new BigDecimal(0));
				if (shareMid != null && shareMid != 0L) {
					Member shareMember = memberService.getByKey(shareMid);
					op.setProductShareMemberId(shareMember.getId()); //设置商品分享用户id
					//商品分享佣金
					op.setProductShareCommision(calcProductShareCommission(op.getPrice(), centreId));
				}

				//拼团活动发起人分佣
				op.setInitiatorCommission(new BigDecimal(0));
				op.setGeneralMemberCommission(new BigDecimal(0));
				if (promoter != null && promoter != 0L) {
					MarketingGroup marketingGroup = marketingGroupService.getMarketingGroupById(activityId);
					Member promoterMember = memberService.getByKey(promoter);
					if (promoterMember != null && marketingGroup != null) {
						if (promoterMember.getIsVip() == 1) { //如果为创客
							op.setInitiatorCommission(calcInitiateCommission(marketingGroup.getGroupPrice(), marketingGroup.getInitiatorCommission()));
						} else if (promoterMember.getIsVip() == 0) {  //如果不为创客为普通会员
							op.setGeneralMemberCommission(calcInitiateCommission(marketingGroup.getGroupPrice(), marketingGroup.getGeneralMemberCommission()));
						}
						op.setInitiatorMemberId(promoterMember.getId());
					}
				}


				//门店店员佣金
				op.setCommision8(new BigDecimal(0));
				if (clerkId != null && clerkId != 0 && pc.getClerkertype() != null && pc.getClerkercommission() != null) {
					//门店店员佣金
					op.setCommision8(calcHeadCommission(pc.getClerkertype(),
							pc.getClerkercommission(), op.getPrice(), op.getTotal()));
				}


					op.setCommision3(new BigDecimal(0));
					op.setReferrals(Long.parseLong("0"));

				op.setCommision4(new BigDecimal(0));
				op.setAgentid(Long.parseLong("0"));
				op.setAvatar(member.getAvatar());
				op.setRealname(member.getRealname());
				op.setGongyiprice(giftBagFlag ? null : pc.getGongyiprice().multiply(BigDecimal.valueOf(mc.getTotal())));
				op.settXiaoqu(giftBagFlag ? null : teamLeader.gettXiaoqu());
				op.setOrdersn(orderSn);
				//用户推荐人
				op.setUserid(member.getUserid() == null ? 0 : member.getUserid());
				//用户推荐人上级
				op.setUpuserid(member.getUpUserid() == null ? 0 : member.getUpUserid());
				//用户推荐代理
				op.setUseragentid(0L);
				op.setUsername(member.getUserName() == null ? "" : member.getUserName());
				op.setUpusername(member.getUpuserName() == null ? "" : member.getUpuserName());
				op.setUseragentName("");
				//拼团订单
				if (isSubimtOrgType == 2) {
					//拼团状态 拼团中
					op.setSpellgroupStu(1);
				} else {
					//不是拼团商品
					op.setSpellgroupStu(0);
				}
				goodsPrice = goodsPrice.add(op.getPrice());
				goodstotal = goodstotal + op.getTotal();
				allweight = allweight.add(op.getWeight() == null ? BigDecimal.ZERO : op.getGongyiprice());
				if (clerkId != null && clerkId != 0) {
					//店员推荐的会员，只给店员佣金，其他的都没有佣金
					//8有佣金，1256就不参与分佣
					op.setCommision1(BigDecimal.ZERO);
					op.setCommision2(BigDecimal.ZERO);
					op.setCommision5(BigDecimal.ZERO);
					op.setCommision6(BigDecimal.ZERO);
				}
				headcommission = headcommission.add(op.getCommision1());
				usercommission = usercommission.add(op.getCommision5());
				superusercommission = superusercommission.add(op.getCommision6());
				ops.add(op);
			}
			order.setHeadcommission(headcommission);
			order.setOrdersn(orderSn);
			order.setOrderType(orderType);
			BigDecimal discountPrice = null;
			if (couponId != null) {
				//计算优惠券金额
				discountPrice = this.calcTicketAmount(couponId, goodsPrice, centreId, productCentreList, cateringType, skuMap, BigDecimal.ZERO);
				order.setDiscountprice(discountPrice);
				order.setTrId(discountPrice == null ? null : couponId);
				couponId = null;
			}
			//商品总价
			order.setGoodsprice(goodsPrice);
			//订单总价
			orderPrice = goodsPrice;
			order.setOrderprice(orderPrice);
			//支付金额
			if (MarketingGroupRulesEnum.MISS.getCode().equals(order.getGroupRules())) {
				payPrice = BigDecimal.ZERO;
			} else {
				payPrice = orderPrice.subtract(order.getDiscountprice() == null ? BigDecimal.ZERO : order.getDiscountprice());
			}
			order.setPayprice(payPrice);
			if (referralsMenber != null) {
				order.setReferrals(referralsMenber.getId() == null ? 0 : referralsMenber.getId());
			}
			order.setCentreId(centre.getCentreId());
			order.setGoodstotal(goodstotal);
			order.setMid(member.getId());
			order.setOpenid(member.getOpenid());
			order.setNickname(member.getNickname());
			order.setAvatar(member.getAvatar());
			order.setRealname(member.getRealname());
			if (null == deliveryAddress) {
				order.setProvince(member.getProvince());
				order.setCity(member.getCity());
				order.setDistrict(member.getArea());
				order.setAddress(member.getAddress());
				order.setSaddress(order.getCity() + order.getDistrict() + order.getAddress());
			} else {
				order.setProvince(deliveryAddress.getProvince());
				order.setCity(deliveryAddress.getCity());
				order.setDistrict(deliveryAddress.getArea());
				order.setAddress(ValidateUtil.isEmptyString(deliveryAddress.getHouseNum()) ? deliveryAddress.getAddress() : deliveryAddress.getAddress() + deliveryAddress.getHouseNum());
				order.setSaddress(deliveryAddress.getArea() + deliveryAddress.getCity() + deliveryAddress.getAddress());
			}
			order.setOutTradeNo(payNo);
			order.setPayMerchantNo(order.getOutTradeNo());
			order.setSname(sname);
			order.setMobile(mobile);
			if (teamLeader != null) {
				order.settXiaoqu(teamLeader.gettXiaoqu());
				order.settMid(teamLeader.getId());
				order.settNickname(teamLeader.getNickname());
				order.setTtMid(teamLeader.getUpTeamid());
				order.setTtNickname(teamLeader.getUpTeamname());
			}
			order.setRemark(houseNo);
			order.setIscomment(iscomment);
			//拼团订单
			if (orderType == ProductType.Spellgroup.getType()) {
				//发起人
				order.setPromoter(promoter);
				//拼团状态 拼团中
				order.setSpellgroupStu(1);
				//带发起人订单id
				if (orderId != null) {
					//发起人拼团订单id
					order.setSgorderId(orderId);
				}
			}
			order.setOrderType(orderType);

			order.setPortType(portType);
			int r = orderMapper.insertSelective(order);

			if (r < 0) {
				throw new BDException(BusinessCode.CREATE_ORDER_ERROR);
			} else {
				//创建定时任务
				createAutoCloseOrderTask(order.getOrdersn(), order.getId(), order.getCentreId());
			}

			if (ValidateUtil.isNotEmptyCollection(usableTeamMiddleList)) {
				usableTeamMiddleList.forEach(item -> {
					item.setOrderId(order.getId());
				});
				usableTeamMiddleMapper.insertList(usableTeamMiddleList);
			}

			resOrderId = order.getId().toString();
			for (OrderProduct op : ops) {
				op.setOrderid(order.getId());
			}
			int i = orderProductMapper.insertSelectiveBatch(ops);
			if (i < 0) {
				throw new BDException(BusinessCode.CREATE_ORDER_ERROR);
			}
			//拼团订单
			if (isSpellgroup != null && isSpellgroup == 1) {
				//不带发起人订单id 发起人是自己
				if (orderId == null) {
					Order record = new Order();
					//订单id
					record.setId(order.getId());
					//拼团发起人订单id
					record.setSgorderId(order.getId());
					//修改拼团人数
					orderMapper.updateByPrimaryKeySelective(record);
				}
			}
			if (order.getTrId() != null) {
				TicketRecord tr = ticketService.getRecordByKey(order.getTrId());
				tr.setUseTime(new Date());
				tr.setOrderId(order.getId());
				tr.setCountUsed(tr.getCountUsed() + 1);
				if (tr.getCountUsed() >= tr.getCount()) {
					tr.setStatus(TicketStatus.USED.getStatus());
				}
				tr.setDeductAmount(order.getDiscountprice());
				ticketService.updateRecord(tr);
				ticketService.addRecordUseInfo(tr, 1, order.getId(), "订单提交，使用优惠券",new TicketRecordUse());
			}
			PlatformConfig config1 = configService.getConfigByKey(ConfigKey.TRADE_CONFIG.name(), null);
			JSONObject configValue = JSONObject.parseObject(config1.getConfigValue());
			String string = configValue.getString("RocketMQ");
			Object object = null;
			if (StringUtils.isNotBlank(string)) {
				JSONObject parseObject = JSON.parseObject(string);
				object = parseObject.get("R_ORDER");
			}
			//同步到MQ中
			if (object != null && "1".equals(object.toString())) {
				OrderMQProducer.sendAsync(JSON.toJSONString(ops), "ORDER_TOPIC", "CANCEL_ORDER", order.getId().toString());
			}
			//直接进行计算
			else {
				orderMq(ops, order.getId());
			}
		}

		return resOrderId;
	}

	/**
	 * 计算拼团发起人发起佣金
	 *
	 * @param price
	 * @param radio
	 * @return
	 */
	private BigDecimal calcInitiateCommission(BigDecimal price, Double radio) {
		try {
			Double commission = radio;
			if (commission != null) {
				//佣金比例
				BigDecimal ratio = new BigDecimal(commission).
						divide(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_DOWN);
				//返回佣金 保留2位小数不四舍五入
				return price.multiply(ratio)
						.setScale(2, BigDecimal.ROUND_DOWN);
			} else {
				return new BigDecimal(0);
			}
		} catch (Exception e) {
			logger.info("计算商品分享佣金错误");
			return new BigDecimal(0);
		}
	}

	@Override
	public Long getWaitOrderId(ListOrderParams params) {
		List<Order> list = orderMapper.listByParams(params);
		if (CollectionUtils.isNotEmpty(list)) {
			Long orderId = list.get(0).getId();
			return orderId;
		}
		return null;
	}

	/**
	 * 得到订单最新的用户头像
	 *
	 * @param productId
	 * @param offset
	 * @param limit
	 * @return
	 */
	@Override
	public PageUtils<OrderHead> getOrderUserHeadImg(Long productId, int offset, int limit) {
		PageUtils<OrderHead> pageUtils = new PageUtils<OrderHead>();
		if (productId == null) {
			logger.info("productId is null", productId);
			return null;
		}
		List<OrderHead> list = orderProductMapper.getOrderUserHeadImg(productId, new RowBounds(offset, limit));
		if (list.size() > 0) {
			pageUtils.setTotal(list.size());
			pageUtils.setRows(list);
		}
		return pageUtils;
	}

	@Override
	public PageUtils<AfterSaleProductVo> listAfterSaleProductList(ListAfterProductParams params, Integer offset,
																  Integer limit) {
		PageUtils<AfterSaleProductVo> pageUtils = new PageUtils<>();
		int total = orderMapper.countAfterSaleProduct(params);
		if (total > 0) {
			List<AfterSaleProductVo> list = orderMapper.listAfterSaleProduct(params, new RowBounds(offset, limit));
			pageUtils.setTotal(total);
			pageUtils.setRows(list);
		}
		return pageUtils;
	}

	@Override
	public Map<String, Object> supplyCount(ShopCountParams shopCountParams, int offset, int limit) {
		if (shopCountParams.getSupplyId() == null) {
			return null;
		}
		Map<String, Object> result = new HashMap<>(4);
		int startH = 20, startM = 30, endH = 20, endM = 0;
		TradeConfig config = configService.getTradeConfig(shopCountParams.getCentreId());
		if (config != null) {
			endH = config.getFreeEndHour() == null ? endH : config.getFreeEndHour();
			endM = config.getFreeEndMin() == null ? endM : config.getFreeEndMin();
			startH = config.getNodeHour() == null ? startH : config.getNodeHour();
			startM = config.getNodeMin() == null ? startM : config.getNodeMin();
		}

		Integer timeType = shopCountParams.getTimeType();
		Date start = shopCountParams.getStart();
		Date end = shopCountParams.getEnd();
		if (TimeType.TODAY.getCode().equals(timeType)) {
			start = DateUtils.getAppointTime(DateUtils.getAddDayDate(new Date(), -1), startH, startM);
			end = DateUtils.getAppointTime(new Date(), endH, endM);
		} else if (TimeType.YESTERDAY.getCode().equals(timeType)) {
			end = DateUtils.getAppointTime(DateUtils.getAddDayDate(new Date(), -1), endH, endM);
			start = DateUtils.getAppointTime(DateUtils.getAddDayDate(new Date(), -2), startH, startM);

		} else {
			start = DateUtils.getAppointTime(DateUtils.getAddDayDate(start, -1), startH, startM);
			end = DateUtils.getAppointTime(end, endH, endM);
		}
		shopCountParams.setStart(start);
		shopCountParams.setEnd(end);

		PageUtils<Map<String, Object>> pageUtils = new PageUtils<>();
		if (shopCountParams.getType() == 0) {
			/**按商品统计**/
			int total = orderProductMapper.countSupplySalesGroupByProduct(shopCountParams);
			if (total > 0) {
				pageUtils.setTotal(total);
				List<Map<String, Object>> list = orderProductMapper.getSupplySalesGroupByProduct(shopCountParams, new RowBounds(offset, limit));
				for (Map<String, Object> item : list) {
					if (shopCountParams.getGroupBy() == null) {
						shopCountParams.setSkuId(null);
						Long productId = (Long) item.get("productId");
						if (item.get("skuId") != null) {
							shopCountParams.setSkuId((Long) item.get("skuId"));
						}
						shopCountParams.setProductId(productId);
					} else {
						shopCountParams.setBaseSkuId(null);
						Long productBaseId = Long.valueOf(item.get("pid") + "");
						if (item.get("baseSkuId") != null) {
							shopCountParams.setBaseSkuId(Long.valueOf(item.get("baseSkuId") + ""));
						}
						shopCountParams.setProductBaseId(productBaseId);
					}
					if (shopCountParams.getSupplyId() != null) {
						item.put("storeRoom", orderProductMapper.countSupplyGroupByStoreroom(shopCountParams));
					}
				}
				pageUtils.setRows(list);
			}
			result.put("countList", pageUtils);

			List<Map<String, Object>> salesTotalList = orderProductMapper.getSupplySaleTotal(shopCountParams);
			if (shopCountParams.getTimeType() == 4) {
				if (salesTotalList != null && salesTotalList.size() > 0 && salesTotalList.get(0) != null) {
					Map<String, Object> map = salesTotalList.get(0);
					if (map != null) {
						map.put("total", pageUtils.getTotal());
						//替换total
						salesTotalList.set(0, map);
					}
				}
			}
			result.put("salesTotal", salesTotalList);
		}
		return result;
	}

	@Override
	public Order getOrderByTradNo(String tradNo) {
		if (StringUtils.isEmpty(tradNo)) {
			return null;
		}
		OrderExample example = new OrderExample();
		example.or().andOutTradeNoEqualTo(tradNo);
		List<Order> list = orderMapper.selectByExample(example);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		return list.get(0);
	}

	@Override
	public void sendGZHOpenMembership(Long centreId, Long mid, Map<String, String> map, String url) {
		PlatformConfig platformConfig = configService.getConfigByKey(ConfigKey.GZHTEMPLATE_CONFIG.name(), centreId);
		TemplateGZHConfig templateGZHConfig = null;
		if (platformConfig == null) {
			logger.info("该商户并未配置公众号模板====null");
			;
		} else {
			templateGZHConfig = JSON.parseObject(platformConfig.getConfigValue(), TemplateGZHConfig.class, Feature.OrderedField);
		}
		//得到用户信息
		Member mem = memberService.getByKey(mid);
		if (mem == null) {
			logger.info("用户不存在！");
		}
		WxNotifyParam notifyParam = new WxNotifyParam();
		List<TemplateParam> paras = new ArrayList<>();
		InformationGZHTemplate informationGZHTemplate = null;


		//以下为特殊部分
		if (templateGZHConfig != null) {
			if (ValidateUtil.isNotEmptyString(templateGZHConfig.getOpenMembershipIdGZH())) {
				informationGZHTemplate = informationGZHTemplateService.findDetail(Long.parseLong(templateGZHConfig.getOpenMembershipIdGZH()));
			}
		}
		//模板id
		Member member = memberMapper.selectByPrimaryKey(mid);
		if (informationGZHTemplate != null && ValidateUtil.isNotEmptyString(templateGZHConfig.getWxOpenMembershipIdGZH()) && ValidateUtil.isNotEmptyObjectOrString(member.getOpenid())) {
			//模板消息
			HashMap<String, Object> result = JSON.parseObject(informationGZHTemplate.getTemplateValue(), LinkedHashMap.class, Feature.OrderedField);
			HashMap<String, Object> resultEntity = JSON.parseObject(informationGZHTemplate.getTemplateEntity(), LinkedHashMap.class, Feature.OrderedField);
			if (result == null) {
				throw new BDException("公众号消息模板参数不存在！");
			} else {
				/*
				通过Map.keySet遍历key和value：
				逻辑解释:
				map里存储的是供选择使用的键值对,
				paras里存的是模板需要的键值对,
				paras的key,为微信服务平台提供的代替换字段名,value为字段名对应的具体值(实体属性)
				 */
				for (String key : result.keySet()) {
					paras.add(new TemplateParam(result.get(key).toString(), map.get(resultEntity.get(key).toString())));
				}

				//三个参数:类型 商户id 链接
				notifyParam.setMessageType(WxMessageType.MESSAGE_TYPE_TEMPLATE.getType());//模板消息
				notifyParam.setCenterId(centreId);
				notifyParam.setUrl(url);
				//三个参数:模板id 公众号端 会员openid
				notifyParam.setTemplateId(templateGZHConfig.getWxOpenMembershipIdGZH());
				notifyParam.setTeminal(WxTerminal.TERMINAL_GZH.getTerminal());
				notifyParam.setGzhOpenId(member.getOpenid());

				//内容字段
				Map<String, String> notifyParamItems = new HashMap<>();
				for (TemplateParam templateParam : paras) {
					notifyParamItems.put(templateParam.getKey(), templateParam.getValue());
				}
				notifyParam.setItems(notifyParamItems);
				wxNotifyService.sendNotify(notifyParam);
			}
		} else {
			logger.info("公众号消息配置错误！");
		}
	}

	@Override
	public JuheOrder getJuheOrderByOutTradeNo(String outTradeNo) {
		return juheOrderMapper.selectOrderByOutTradeNo(outTradeNo);
	}

	@Override
	public List<Order> getOrderByOutTradeNo(String outTradeNo) {
		// TODO Auto-generated method stub
		return orderMapper.selectOrderByOutTradeNo(outTradeNo);
	}


	@Override
	public BigDecimal calcTicketAmountJuhepay(Long trId, BigDecimal orderPrice, Long centreId) {
		if (trId == null) {
			return BigDecimal.ZERO;
		}
		Map map = new HashMap<>();
		map.put("ticketId", trId);
		map.put("centreId", centreId);
		TicketRecord tr = ticketRecordMapper.getTicketRecordsByParam(map);
		if (tr == null) {
			return BigDecimal.ZERO;
		}
		ticketService.giftPacksAfterSale(tr);
		BigDecimal amount = tr.getAmount();
		Integer type = tr.getType();
		if (amount == null || type == null) {
			throw new BDException(BusinessCode.TICKET_RECORD_ERROR);
		}
		if (TicketType.SINGLE_COUPON.getCode() == type) {
			return orderPrice;
		} else if (TicketType.VOUCHER.getCode() == type) {
			return amount;
		} else if (!(TicketType.PINKAGE.getCode() == type)) {
			return amount.multiply(orderPrice).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP);
		} else {
			//免邮卷不能在聚合支付使用;
			return BigDecimal.ZERO;
		}
	}

	@Override
	public JuheOrder createJuheOrder(Long mid, Long centerId, Long teamId, String userId, String payAmount, String code, Integer payType, BigDecimal payPrice, Long trId) {
		JuheOrder order = new JuheOrder();
		order.setUserId(userId);
		order.setChanelCode(code);
		order.setPayType(payType);
		order.setPayTime(new Date());
		order.setRemark(mid.toString());
		order.setMid(mid);
		order.setOrderprice(new BigDecimal(payAmount));
		order.setOrdersn(getSn("D"));
		order.setOutTradeNo("JH_".concat(order.getOrdersn()));
		order.setCenterId(centerId);
		order.setTeamId(teamId);
		order.setPayprice(payPrice);
		order.setTrId(trId);
		juheOrderMapper.insertSelective(order);
		return order;
	}

	/**
	 * 得到跑p任务拼团中订单
	 *
	 * @return
	 */
	public List<OrderProductDetailVo> getTaskSpellGroupOrd() {
		return orderMapper.getTaskSpellGroupOrd();
	}

	@Override
	public void autoCompleteOrder(List<OrderProduct> ops, Long centreId, Double exchange) {
		Integer totalCredit = 0;
		String ordersn = ops.get(0).getOrdersn();
		Long orderid = ops.get(0).getOrderid();
		for (OrderProduct op : ops) {

			logger.info("完成订单商品：{}", op.getId());

			/**积分商品发放积分**/
			if (op.getCredit() != null && op.getCredit() > 0) {
				totalCredit = totalCredit + op.getCredit();

				memberIntegralService.grantIntegralNew(op.getMid(), centreId, op.getPrice(), op.getCredit(), op.getOrderid(), op.getId(), op.getNickname(), op.getProductName());
			}


			/**计算供应商成本start**/
			//通过商品编号获取供应商信息
			//构建变更流水
			ProductCentre pc = productCentreService.getProductCentre(op.getProductId());//查询商户商品
			BigDecimal allmoney = null;
			if (pc != null && (pc.getProductId() == null || pc.getProductId() == 0)) {
				allmoney = op.getCostprice().multiply(new BigDecimal(op.getTotal()));//计算站点供应商资金

				//扣除商户余额
				centreService.supplyDeductAmount(centreId, allmoney, op.getOrdersn(), op.getId());

			} else {
				logger.error("-----------------商品为空:{}", op.getProductId());
				Product product = productService.getByKeyWithCache(pc.getProductId());
				allmoney = product.getCostprice().multiply(new BigDecimal(op.getTotal()));//计算平台供应商资金
			}


		}

		//结算该笔订单所消耗的积分抵扣金额
		if (totalCredit != null && totalCredit.doubleValue() > 0) {

			CentreAmount centreAmount = centreAmountMapper.getByKey(centreId);
			//结算下一笔订单
			AmountLog al = new AmountLog();
			al.setOrderId(orderid);
			al.setCentreId(centreId);
			al.setOrderSn(ordersn);
			BigDecimal credit1 = new BigDecimal(totalCredit + "");
			BigDecimal credit = credit1.divide(BigDecimal.valueOf(exchange), 2, BigDecimal.ROUND_HALF_UP);
			al.setMoney(credit.negate());//扣减
			al.setFlowType(12);//站点结算扣除积分抵扣金额
			BigDecimal amount = centreAmount.getAmount().subtract(credit);
			al.setRemark("订单平台结算给站点扣除积分抵扣金额：" + totalCredit + " 订单号:" + ordersn + "【变动金额" + centreAmount.getAmount() + "->" + amount + "】");
			al.setBeforeamount(centreAmount.getAmount());
			al.setAfteramount(amount);
			amountLogMapper.saveAmountLog(al);
			centreAmountMapper.deductAmount(centreId, credit);

		}
	}

	@Override
	public List<OrderProduct> listSuccessOrderProductsTime(Date sevenDate, Date start, Long centreId) {
		if (sevenDate == null) {
			sevenDate = DateUtils.getDateStartTime(DateUtils.getAddDayDate(new Date(), -0));
		}
		return orderProductMapper.listSuccessOrderProducts(sevenDate, start, centreId);
	}

	@Override
	public List<OrderProduct> listOrderProducts(Long orderId, Integer status, Integer isKuaidi) {
		OrderProductExample example = new OrderProductExample();
		OrderProductExample.Criteria criteria = example.createCriteria();
		if (orderId != null) {
			criteria.andOrderidEqualTo(orderId);
		}
		if (status != null) {
			criteria.andStatusEqualTo(status);

		}
		if (isKuaidi != null) {
			criteria.andIsKuaidiEqualTo(isKuaidi);
		}
		return orderProductMapper.selectByExample(example);
	}

	@Override
	public List<Order> listSuccessOrders(Date sevenDate, Date start, Long centreId, int offset, int limit) {
		if (sevenDate == null) {
			sevenDate = DateUtils.getDateStartTime(DateUtils.getAddDayDate(new Date(), -0));
		}
		return orderMapper.listSuccessOrders(sevenDate, start, centreId, new RowBounds(offset, limit));
	}


	/**
	 * 提交营销活动的订单
	 *
	 * @param req 订单提交逻辑
	 * @return
	 * @throws ParseException
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public String submitActivtyOrder(OrderReq req) throws ParseException {
		Member member = memberService.getByKey(req.getMemberId());
		if (member == null) {
			throw new BDException(BusinessCode.MEMBER_INFO_ISNULL);
		}

		//判断是否超过礼包限购
		//除订单状态为state=-1以外，均计入限购次数
		//礼包对应的订单类型为ordertype=11
		//取centreid
		if (req.getOrderType().equals(ProductType.FreeCharge.getType())) {
			List<Order> orderList = null;
			for (MemberCartVo memberCartVo : req.getProducts()) {
				Activity activity = activityMapper.selectByPrimaryKey(memberCartVo.getProductId());
				//查询该用户是否有该购买权限
				if (activity.getShopProductAuthorityId() != null && activity.getShopProductAuthorityId() != 0L) {
					MemberProductAuthority memberProductAuthority = memberProductAuthorityMapper.getByProductAuthorityIdAndMid(activity.getShopProductAuthorityId(), member.getId());
					if (memberProductAuthority == null) {
						throw new BDException(BusinessCode.ACTIVITY_AUTHORITY_ERROR);
					}
				}


				Integer limitNum = activity.getJoinNum();
				int num = 0;

				if (limitNum != null && limitNum > 0) {
					//用mapper里的listByParams对数据库订单商品进行查找
					ListOrderParams params = new ListOrderParams();
					params.setOrderType(ProductType.FreeCharge.getType());
					params.setCentreId(memberCartVo.getCentreId());
					params.setMid(memberCartVo.getMid());
					orderList = orderMapper.listByParams(params);
					//此处得到centreid、mid、orderType和当前待生成订单一致的所有订单集合

				/*此处遍历集合里的每个订单，找到购物项和当前订单一致的订单，进行计算；
				注意免单礼包类订单只有单一购物项，且数量恒定为1，但此处并未采用简便写法*/
					for (Order order : orderList) {
						//检索尚未取消的订单
						if (order.getStatus() != OrderStatus.cancel.getCode()) {
							List<OrderProduct> orderProductList = orderProductMapper.getByOrderId(order.getId());
							//如果历史订单的购物项和当前订单购物项为同一事物
							OrderProduct exitOrderProduct = orderProductList.get(0);
							if (exitOrderProduct.getProductId().equals(req.getProducts().get(0).getProductId())) {
								num += exitOrderProduct.getTotal();
							}
						}
					}
					num += memberCartVo.getTotal();
					//如果num大于限购数量，则交易不可成立
					if (num > limitNum) {
						throw new BDException(BusinessCode.BUY_MAX_LG_TOO_MANY);
					}
				}
				//判断大礼包下面有没有  优惠券和商品
				ActivityProductExample example = new ActivityProductExample();
				example.createCriteria().andActivityIdEqualTo(activity.getId()).andTypeEqualTo(ActivityProductType.FREE_CHARGE.getType());
				List<ActivityProduct> list = activityProductMapper.selectByExample(example);
				boolean flag = false;
				for (ActivityProduct model : list) {
					String freechargeId = model.getFreechargeId();
					String couponIds = model.getCouponIds();

					if (StringUtils.isNotEmpty(freechargeId)) {
						flag = true;
						break;
					}
					if (StringUtils.isNotEmpty(couponIds)) {
						flag = true;
						break;
					}
				}
				if (!flag) {
					throw new BDException(BusinessCode.BUY_MAX_TOO_MANY);
				}

				req.setTeamId(list.get(0).getProductId());
			}
		}

		String sname = StringUtils.isNotEmpty(req.getSname()) ? req.getSname() : member.getNickname();
		String mobile = req.getMobile();
		if (StringUtils.isEmpty(mobile)) {
			mobile = member.getMobile();
		}
		String iscomment = StringUtils.isEmpty(req.getIscomment()) ? "" : req.getIscomment();

		if (StringUtils.isEmpty(sname)) {
			sname = StringUtils.isNotEmpty(member.getRealname()) == true ? member.getRealname() : member.getNickname();
		}

		List<Map<String, String>> list = new ArrayList<>();
		String orderId = "";
		try {
			logger.info("---进入普通订单---");
			if (req.getOrderType() == null) {
				req.setOrderType(0);
			}
			//校验库存,创建订单,发送消息
			orderId = this.newCheckActivityStock(member, req.getProducts(), sname, mobile, req.getHouseNo(), list, req.getCouponId(), member.getAddress()
					, req.getAllweight(), req.getDispatchid(), req.getDispatchprice(), iscomment, req.getIsSpellgroup(), req.getOrderId(),
					req.getPromoter(), req.getAppointmentName(), req.getAppointmentMobile(), req.getAppointmentDate(), req.getSeatNum(), req.getCateringType()
					, req.getDispatchtype(), req.getClerkId(), req.getOrderType(), req.getAddressId(), req.getTeamId(), req.getActivityId(), req.getShareMid()
					, req.getPortType(), req.getPlateType(), req.getUsableTeamMiddleList());

			logger.info("---结束普通订单---");
			if (StringUtils.isEmpty(orderId)) {
				logger.error("创建订单失败平台订单编号为空");
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			//如果抛出异常,把redis回滚
			logger.error("库存集合:{}", list.toString());
			if (CollectionUtils.isNotEmpty(list)) {
				for (Map<String, String> map : list) {
					String cache_key_product_sku_sale = map.get("STOCK_GIFT_PACKS_VERSION_TOTAL");
					String CACHE_KEY_PRODUCT_SALE = map.get("CACHE_KEY_PRODUCT_SALE_TOTAL");
					String CACHE_KEY_PRODUCT_CENTRE_SKU_SALE = map.get("CACHE_KEY_PRODUCT_CENTRE_SKU_SALE_TOTAL");
					String CACHE_KEY_PRODUCT_CENTRE_SALE = map.get("CACHE_KEY_PRODUCT_CENTRE_SALE_TOTAL");
					String STOCK_GIFT_PACKS_VERSION = map.get("STOCK_GIFT_PACKS_VERSION");
					String STOCK_GIFT_PACKS_VERSION_TOTAL = map.get("STOCK_GIFT_PACKS_VERSION_TOTAL");
					if (cache_key_product_sku_sale != null) {
						logger.error("创建订单失败平台sku:{}", map.get("CACHE_KEY_PRODUCT_SKU_SALE"));
						localRedis.increamNum(map.get("CACHE_KEY_PRODUCT_SKU_SALE"), -Integer.valueOf(cache_key_product_sku_sale));
					}
					if (CACHE_KEY_PRODUCT_SALE != null) {
						logger.error("创建订单失败平台:{}", map.get("CACHE_KEY_PRODUCT_SALE"));
						localRedis.increamNum(map.get("CACHE_KEY_PRODUCT_SALE"), -Integer.valueOf(CACHE_KEY_PRODUCT_SALE));
					}
					if (CACHE_KEY_PRODUCT_CENTRE_SKU_SALE != null) {
						logger.error("创建订单失败站点sku:{}", map.get("CACHE_KEY_PRODUCT_CENTRE_SKU_SALE"));
						localRedis.increamNum(map.get("CACHE_KEY_PRODUCT_CENTRE_SKU_SALE"), -Integer.valueOf(CACHE_KEY_PRODUCT_CENTRE_SKU_SALE));
					}
					if (CACHE_KEY_PRODUCT_CENTRE_SALE != null) {
						logger.error("创建订单失败站点:{}", map.get("CACHE_KEY_PRODUCT_CENTRE_SALE"));
						localRedis.increamNum(map.get("CACHE_KEY_PRODUCT_CENTRE_SALE"), -Integer.valueOf(CACHE_KEY_PRODUCT_CENTRE_SALE));
					}
					if (STOCK_GIFT_PACKS_VERSION != null) {
						logger.error("创建订单失败站点:{}", map.get("CACHE_KEY_PRODUCT_CENTRE_SALE"));
						localRedis.increamNum(STOCK_GIFT_PACKS_VERSION, -Integer.valueOf(STOCK_GIFT_PACKS_VERSION_TOTAL));
					}
				}
			}
			if (e instanceof BDException) {
				throw e;
			} else {
				throw new BDException(BusinessCode.CREATE_ORDER_ERROR);
			}

		}
		return orderId;
	}

    /**
     * 校验库存，封装订单商品对象,创建订单,发送消息
     *
     * @return
     */
    private String newCheckActivityStock(Member member, List<MemberCartVo> products, String sname, String mobile, String houseNo, List list, Long couponId,
                                         String address, String alldweight, String dispatchid, String dispatchprice, String iscomment,
                                         Integer isSpellgroup, Long orderId, Long promoter, String appointmentName, String appointmentMobile,
                                         Date appointmentDate, String seatNum, Integer cateringType, Integer dispatchtype, Long clerkId, Integer orderType,
                                         Long addressId, Long teamId, Long activityId, Long shareMid, Integer portType, Integer plateType, List<UsableTeamMiddle> usableTeamMiddleList) throws ParseException {

        logger.info("---进入普通订单新增---");
        Member teamLeader = null;

        //没有选门店
        if (teamId != null) {
            teamLeader = memberService.getByKey(teamId);
            if (teamLeader == null) {
                throw new BDException(BusinessCode.MEMBER_NOT_BIND_TEAM);
            }
        }
        List<Centre> centres = centreService.listAllCentres();
        if (CollectionUtils.isEmpty(centres)) {
            logger.info("not found centre info! auto check order delivery end...");
            return null;
        }
        Address deliveryAddress = null;
        if (addressId != null) {
            deliveryAddress = addressService.getByKey(addressId);
        }

        String payNo = null;
        String resOrderId = null;
        for (Centre centre : centres) {
            //centreID不匹配，则跳过
            List<MemberCartVo> collect = products.stream().filter(MemberCartVo -> MemberCartVo.getCentreId().toString().equals(centre.getCentreId().toString())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(collect)) {
                continue;
            }
            Order order = new Order();
            BigDecimal orderPrice = new BigDecimal(0d);
            BigDecimal goodsPrice = new BigDecimal(0d);
            BigDecimal allIntegral = new BigDecimal(0d);
            BigDecimal payPrice = new BigDecimal(0d);
            Integer goodstotal = 0;
            BigDecimal headcommission = new BigDecimal(0d);
            BigDecimal allweight = new BigDecimal(0d);
            //用户推荐人佣金
            BigDecimal usercommission = new BigDecimal(0d);
            //用户推荐人上级佣金
            BigDecimal superusercommission = new BigDecimal(0d);
            Long centreId = null;
            String orderSn = getSn("D");
            if (payNo == null) {
                String sn = DateUtils.format(new Date(), "mmss");
                payNo = "X_OC_".concat(orderSn).concat("_").concat(sn);
            }
            List<OrderProduct> ops = new ArrayList<>();
            List<ProductCentre> productCentreList = new ArrayList<>();
            Map<String, String> skuMap = new HashMap<String, String>(16);
            //版本推荐人
            Member referralsMenber = null;

            for (MemberCartVo mc : collect) {
                OrderProduct op = new OrderProduct();
                //套装商品
                if (ProductType.Package.getType() == orderType) {
                    Long activityProductId = mc.getProductId();
                    ActivityProduct activityProduct = activityProductMapper.selectByPrimaryKey(activityProductId);
                    Activity activity = activityMapper.selectByPrimaryKey(activityProduct.getActivityId());
                    //优惠券打包，将优惠券对应的信息，设置到订单详情中
                    if (ActivityMode.PACKAGE_COUPON.getType() == activity.getMode()) {
                        Ticket ticket = ticketService.getByKey(activityProduct.getProductId());
                        op.setThumb(ticket.getTicketImg());
                        op.setCartId(mc.getId());
                        op.setMid(member.getId());
                        op.setOpenid(member.getOpenid());
                        op.setSname(sname);
                        op.setMobile(mobile);
                        op.setNickname(member.getNickname());
                        op.setProductId(activityProduct.getProductId());
                        op.setIsLiansuo(activity.getTeamId() == null ? 0 : 1);
                        op.setSelProductId(activityProduct.getProductId());
                        op.setTotal(mc.getTotal());
                        op.setMarketprice(activityProduct.getActivityPrice());
                        op.setCostprice(activityProduct.getActivityPrice());
                        op.setProductprice(activityProduct.getActivityPrice());
                        op.setShortTitle(activityProduct.getProductName());
                        op.setProductName(activityProduct.getProductName());
                        op.setCredit(0);
                        op.setIscredits(0);
                        op.setIsKuaidi(mc.getIsKuaidi());
                        if (null == teamLeader) {
                            teamLeader = memberService.getByKey(activity.getTeamId());
                        }
                        op.settMid(teamLeader.getId());
                        op.settNickname(teamLeader.getNickname());
                        op.setTtMid(teamLeader.getUpTeamid());
                        op.setTtNickname(teamLeader.getUpTeamname());
                        ops.add(op);

                        goodsPrice = goodsPrice.add(activityProduct.getActivityPrice());
                        goodstotal = goodstotal + op.getTotal();
                    } else {
                        Long centreProductId = mc.getProductId();
                        ProductCentre pc = productCentreService.getByKeyWithCache(centreProductId);
                        if (null == teamLeader) {
                            teamLeader = memberService.getByKey(pc.getLiansuoid());
                        }
                        if (pc == null) {
                            throw new BDException(BusinessCode.ORDER_PRODUCTS_ERROR);
                        }
                        productCentreList.add(pc);
                        skuMap.put(pc.getId().toString(), mc.getSpecs());
                        if (pc.getMaxbuy() > 0 && pc.getMaxbuy() < mc.getTotal()) {
                            throw new BDException(BusinessCode.BUY_MAX_TOO_MANY);
                        }
                        centreId = pc.getCentreId();
                        int t = orderProductMapper.countMidProductNums(member.getId(), centreProductId);
                        if (pc.getUsermaxbuy() > 0 && pc.getUsermaxbuy() <= t) {
                            throw new BDException(BusinessCode.BUY_MAX_LG_TOO_MANY);
                        }

                        ProductSkuCentre skuCentre = null;
                        Long centreSkuId = mc.getSkuId();
                        if (pc.getHasoption() != null && pc.getHasoption() == 1) {
                            //有SKU
                            if (mc.getSkuId() == null) {
                                throw new BDException(BusinessCode.ORDER_PRODUCT_SKU_ERROR);
                            }
                            skuCentre = productCentreService.getSkuByKeyWithCache(mc.getSkuId());
                            if (skuCentre == null) {
                                throw new BDException(BusinessCode.ORDER_PRODUCT_SKU_ERROR);
                            }
                        }
                        //校验商品库存
                        Long platformProductId = pc.getProductId();
                        Map<String, String> map = new HashMap<>();
                        Integer total = mc.getTotal();
                        if (platformProductId != null && platformProductId > 0) {
                            //平台商品
                            Product base = productService.getByKeyWithCache(platformProductId);
                            if (base == null) {
                                throw new BDException(BusinessCode.ORDER_PRODUCTS_ERROR);
                            }
                            if (base.getHasoption() != null && base.getHasoption() == 1) {
                                //平台带SKU商品
                                ProductSku sku = productSkuService.getSkuByKeyWithCache(skuCentre.getSkuId());
                                if (sku == null) {
                                    throw new BDException(BusinessCode.ORDER_PRODUCT_SKU_ERROR);
                                }
                                op.setSkuId(sku.getId());
                                long sSale = localRedis.increamNum(CACHE_KEY_PRODUCT_SKU_SALE.concat(String.valueOf(sku.getId())), total);
                                if (sku.getStock() < sSale) {
                                    logger.info("平台带SKU商品:{},销量已超过限制！扣减销量", sku.getTitle());
                                    localRedis.increamNum(CACHE_KEY_PRODUCT_SKU_SALE.concat(String.valueOf(sku.getId())), -total);
                                    throw new BDException(pc.getTitle().concat("已卖完,请删除该商品"));
                                }
                                map.put("CACHE_KEY_PRODUCT_SKU_SALE", CACHE_KEY_PRODUCT_SKU_SALE.concat(String.valueOf(sku.getId())));
                                map.put("CACHE_KEY_PRODUCT_SKU_SALE_TOTAL", total.toString());
                            }

                            long sale = localRedis.increamNum(CACHE_KEY_PRODUCT_SALE.concat(String.valueOf(platformProductId)), total);
                            if (base.getTotal() <= sale) {
                                ProductCentre productCentre = new ProductCentre();
                                productCentre.setDisplayorder(0);
                                productCentre.setProductId(platformProductId);
                                //修改排序
                                productCentreMapper.updateProductCentre(productCentre);
                            }
                            if (base.getTotal() < sale) {
                                localRedis.increamNum(CACHE_KEY_PRODUCT_SALE.concat(String.valueOf(platformProductId)), -total);
                                throw new BDException(pc.getTitle().concat("已卖完,请删除该商品"));
                            }
                            map.put("CACHE_KEY_PRODUCT_SALE", CACHE_KEY_PRODUCT_SALE.concat(String.valueOf(platformProductId)));
                            map.put("CACHE_KEY_PRODUCT_SALE_TOTAL", total.toString());
                        } else {
                            //商户自卖商品
                            if (pc.getHasoption() != null && pc.getHasoption() == 1) {
                                //有SKU
                                op.setSkuId(skuCentre.getId());
                                long sSale = localRedis.increamNum(CACHE_KEY_PRODUCT_CENTRE_SKU_SALE.concat(String.valueOf(centreSkuId)), total);
                                if (skuCentre.getStock() < sSale) {
                                    localRedis.increamNum(CACHE_KEY_PRODUCT_CENTRE_SKU_SALE.concat(String.valueOf(centreSkuId)), -total);
                                    throw new BDException(pc.getTitle().concat("已卖完,请删除该商品"));
                                }
                                map.put("CACHE_KEY_PRODUCT_CENTRE_SKU_SALE", CACHE_KEY_PRODUCT_CENTRE_SKU_SALE.concat(String.valueOf(centreSkuId)));
                                map.put("CACHE_KEY_PRODUCT_CENTRE_SKU_SALE_TOTAL", total.toString());
                            }
                            long sale = localRedis.increamNum(CACHE_KEY_PRODUCT_CENTRE_SALE.concat(String.valueOf(pc.getId())), total);
                            if (pc.getTotal() <= sale) {
                                ProductCentre productCentre = new ProductCentre();
                                productCentre.setDisplayorder(0);
                                productCentre.setId(pc.getId());
                                //修改排序
                                productCentreMapper.updateByPrimaryKeySelective(productCentre);
                            }
                            if (pc.getTotal() < sale) {
                                localRedis.increamNum(CACHE_KEY_PRODUCT_CENTRE_SALE.concat(String.valueOf(pc.getId())), -total);
                                throw new BDException(pc.getTitle().concat("已卖完,请删除该商品"));
                            }
                            map.put("CACHE_KEY_PRODUCT_CENTRE_SALE", CACHE_KEY_PRODUCT_CENTRE_SALE.concat(String.valueOf(pc.getId())));
                            map.put("CACHE_KEY_PRODUCT_CENTRE_SALE_TOTAL", total.toString());
                            //op.setSelProductId(pc.getId());
                        }
                        list.add(map);
                        op.setCartId(mc.getId());
                        op.setMid(member.getId());
                        op.setOpenid(member.getOpenid());
                        op.setSname(sname);
                        op.setMobile(mobile);
                        op.setNickname(member.getNickname());
                        op.setProductId(pc.getId());
                        op.setIsLiansuo(pc.getLiansuoid() == null ? 0 : 1);
                        op.setSelProductId(pc.getProductId());
                        op.setProductCode(pc.getGoodscode());
                        op.setTotal(mc.getTotal());
                        op.setThumb(pc.getThumb());
                        if (null != pc.getProductId() && pc.getProductId() > 0) {
                            op.setBaseproductid(String.valueOf(pc.getProductId()));
                        }
                        BigDecimal marketPrice = pc.getMarketprice();
                        //vip商户数据集合
                        List<String> strlist = Arrays.asList(member.getVipofcentreId().split("-"));
                        //用户是这个商户的vip
                        if (member.getIsVip() == 1 && strlist.indexOf(centre.getCentreId().toString()) != -1) {
                            if (pc.getVipprice() != null && pc.getVipprice().doubleValue() > 0 && pc.getIsvip() == 1) {
                                marketPrice = pc.getVipprice();
                            }
                        }
                        op.setMarketprice(marketPrice);
                        op.setCostprice(pc.getCostprice());
                        op.setProductprice(pc.getProductprice());
                        op.setWeight(pc.getWeight().multiply(BigDecimal.valueOf(mc.getTotal())));
                        op.setShortTitle(pc.getShortTitle());
                        op.setProductName(pc.getTitle());
                        op.setSpecTitle(pc.getSpecTitle());
                        op.setUnit(pc.getUnit());
                        op.setCredit(0);
                        op.setIscredits(0);
                        if (pc.getCredit() > 0) {
                            op.setCredit(new BigDecimal(pc.getCredit() * mc.getTotal()).intValue());
                            op.setIscredits(1);
                        }

                        op.setIsKuaidi(mc.getIsKuaidi());
                        op.setHeadtype(pc.getHeadtype());
                        op.setSuperiortype(pc.getSuperiortype());
                            op.setHeadcommission(pc.getHeadcommission());

                        op.setSuperiorcommission(pc.getSuperiorcommission());
                        op.setUsertype(pc.getUsertype());
                        op.setUsercommission(pc.getUsercommission());
                        op.setSuperusertype(pc.getSuperusertype());
                        op.setSuperusercommission(pc.getSuperusercommission());
                        //多规格商品
                        if (pc.getHasoption() == 1) {
                            op.setOptionname(skuCentre.getTitle());
                            op.setHeadtype(skuCentre.getHeadtype());
                            op.setSuperiortype(pc.getSuperiortype());
                            op.setHeadcommission(pc.getHeadcommission());
                            op.setSuperiorcommission(pc.getSuperiorcommission());

                            //团购多规格产品价格计算
                            if (ProductType.Spellgroup.getType() == orderType) {
                                MarketingGroupSku marketingGroupSku = marketingGroupService.getMarketingGroupSkuByActivityId(activityId, mc.getSkuId());
                                if (null != marketingGroupSku) {
                                    op.setMarketprice(marketingGroupSku.getGroupPrice());
                                }
                            }
                            //普通多规格商品价格获取
                            else {
                                if (skuCentre.getMarketprice() != null) {
                                    op.setMarketprice(skuCentre.getMarketprice());
                                    if (member.getIsVip() == 1) {
                                        if (skuCentre.getVipprice() != null && skuCentre.getVipprice().doubleValue() > 0 && pc.getIsvip() == 1) {
                                            op.setMarketprice(skuCentre.getVipprice());
                                        }
                                    }
                                }
                            }
                            if (skuCentre.getProductprice() != null) {
                                op.setProductprice(skuCentre.getProductprice());
                            }
                            if (skuCentre.getWeight() != null) {
                                op.setWeight(skuCentre.getWeight().multiply(BigDecimal.valueOf(mc.getTotal())));
                            }
                            if (skuCentre.getCostprice() != null && skuCentre.getCostprice().compareTo(BigDecimal.ZERO) == 1) {
                                op.setCostprice(skuCentre.getCostprice());
                            }
                            if (StringUtils.isNotEmpty(skuCentre.getThumb())) {
                                op.setThumb(skuCentre.getThumb());
                            }
                        }
                        //拼团商品，重新计算你团商品的价格
                        else if (orderType == ProductType.Spellgroup.getType()) {
                            MarketingGroup marketingGroup = marketingGroupService.getMarketingGroupById(activityId);
                            op.setMarketprice(marketingGroup.getGroupPrice());
                        }
                        //商品总价格=商品单价*商品数量，这里是实际支付的金额
                        op.setPrice(op.getMarketprice().multiply(BigDecimal.valueOf(mc.getTotal())));
                        if (pc.getIsKuaidi() == 0) {
                            op.setProvince(teamLeader.gettProvince());
                            op.setCity(teamLeader.gettCity());
                            op.setDistrict(teamLeader.gettArea());
                            op.setAddress(teamLeader.gettShopname());
                        } else {
                            op.setProvince(member.getProvince());
                            op.setCity(member.getCity());
                            op.setDistrict(member.getArea());
                            op.setAddress(member.getAddress());
                        }

                        op.setSaddress(op.getProvince() + op.getCity() + op.getDistrict() + op.getAddress());
                        op.settMid(teamLeader.getId());
                        op.settNickname(teamLeader.getNickname());
                        op.setTtMid(teamLeader.getUpTeamid());
                        op.setTtNickname(teamLeader.getUpTeamname());
                        op.setCommision1(calcHeadCommission(op.getHeadtype(), op.getHeadcommission(), op.getPrice(), op.getTotal()));
                        op.setCommision2(new BigDecimal(0));
                        if (teamLeader.getUpTeamid() != null) {
                            op.setCommision2(calcHeadCommission(op.getSuperiortype(), op.getSuperiorcommission(), op.getPrice(), op.getTotal()));
                        }
                        //用户推荐佣金
                        op.setCommision5(new BigDecimal(0));
                        //用户有推荐人
                        if (member.getUserid() != null) {
                            op.setCommision5(calcHeadCommission(pc.getUsertype(),
                                    pc.getUsercommission(), op.getPrice(), op.getTotal()));
                        }
                        //用户推荐人上级佣金
                        op.setCommision6(new BigDecimal(0));
                        //用户有推荐人上级
                        if (member.getUpUserid() != null) {
                            op.setCommision6(calcHeadCommission(pc.getSuperusertype(),
                                    pc.getSuperusercommission(), op.getPrice(), op.getTotal()));
                        }
                        //用户代理佣金
                        op.setCommision7(new BigDecimal(0));
                        op.setAccountManagerCommision(new BigDecimal(0));

                        //商品分享佣金
                        op.setProductShareCommision(new BigDecimal(0));
                        if (shareMid != null && shareMid != 0L) {
                            Member shareMember = memberService.getByKey(shareMid);
                            op.setProductShareMemberId(shareMember.getId()); //设置商品分享用户id
                            //商品分享佣金
                            op.setProductShareCommision(calcProductShareCommission(op.getPrice(), centreId));
                        }

                        //门店店员佣金
                        op.setCommision8(new BigDecimal(0));
                        if (clerkId != null && clerkId != 0) {
                            //门店店员佣金
                            op.setCommision8(calcHeadCommission(pc.getClerkertype(),
                                    pc.getClerkercommission(), op.getPrice(), op.getTotal()));
                        }

						op.setCommision3(new BigDecimal(0));
						op.setReferrals(Long.parseLong("0"));
						op.setCommision4(new BigDecimal(0));
						op.setAgentid(Long.parseLong("0"));
                        op.setAvatar(member.getAvatar());
                        op.setRealname(member.getRealname());
                        op.setGongyiprice(pc.getGongyiprice().multiply(BigDecimal.valueOf(mc.getTotal())));
                        op.settXiaoqu(teamLeader.gettXiaoqu());
                        op.setOrdersn(orderSn);
                        //用户推荐人
                        op.setUserid(member.getUserid() == null ? 0 : member.getUserid());
                        //用户推荐人上级
                        op.setUpuserid(member.getUpUserid() == null ? 0 : member.getUpUserid());
                        //用户推荐代理
                        op.setUseragentid(0L);
                        op.setUsername(member.getUserName() == null ? "" : member.getUserName());
                        op.setUpusername(member.getUpuserName() == null ? "" : member.getUpuserName());
                        op.setUseragentName("");
                        //拼团订单
                        if (isSpellgroup != null && isSpellgroup == 1) {
                            //拼团状态 拼团中
                            op.setSpellgroupStu(1);
                        } else {
                            //不是拼团商品
                            op.setSpellgroupStu(0);
                        }
                        goodsPrice = goodsPrice.add(op.getPrice());
                        goodstotal = goodstotal + op.getTotal();
                        allweight = allweight.add(op.getWeight());
                        if (clerkId != null && clerkId != 0) {
                            //店员推荐的会员，只给店员佣金，其他的都没有佣金
                            //8有佣金，1256就不参与分佣
                            op.setCommision1(BigDecimal.ZERO);
                            op.setCommision2(BigDecimal.ZERO);
                            op.setCommision5(BigDecimal.ZERO);
                            op.setCommision6(BigDecimal.ZERO);
                        }
                        headcommission = headcommission.add(op.getCommision1());
                        usercommission = usercommission.add(op.getCommision5());
                        superusercommission = superusercommission.add(op.getCommision6());
                        ops.add(op);
                    }
                } else if (ProductType.FreeCharge.getType() == orderType) {
                    Activity activity = activityMapper.selectByPrimaryKey(mc.getProductId());
                    Date nowDate = new Date();
                    if (nowDate.after(activity.getEndTime())) {
                        throw new BDException("大礼包已过活动期，无法购买！");
                    }
                    //查询大礼包中包含的优惠券是否充足
                    ticketService.giftPacksTickets(activity.getId());

                    op.setCartId(mc.getId());
                    op.setMid(member.getId());
                    op.setOpenid(member.getOpenid());
                    op.setSname(sname);
                    op.setMobile(mobile);
                    op.setNickname(member.getNickname());
                    op.setProductId(activity.getId());
                    op.setIsLiansuo(activity.getTeamId() == null ? 0 : 1);
                    op.setSelProductId(activity.getId());
                    op.setTotal(1);//免单活动，数量为1
                    op.setThumb(activity.getThumb());

                    if (member.getIsVip() == 1 && activity.getVipPrice() != null && activity.getVipPrice().compareTo(BigDecimal.ZERO) > 0) {
                        op.setMarketprice(activity.getVipPrice());
                        goodsPrice = goodsPrice.add(activity.getVipPrice());
                    } else {
                        op.setMarketprice(activity.getActivityPrice());
                        goodsPrice = goodsPrice.add(activity.getActivityPrice());
                    }

                    allIntegral = allIntegral.add(activity.getConsumptionIntegral());
                    op.setPayIntegral(activity.getConsumptionIntegral());
                    op.setCostprice(activity.getActivityPrice());
                    op.setProductprice(activity.getActivityPrice());
                    op.setShortTitle(activity.getActivityName());
                    op.setProductName(activity.getActivityName());
                    op.setCredit(0);
                    op.setIscredits(0);
                    op.setIsKuaidi(mc.getIsKuaidi());
                    ops.add(op);

                    goodstotal = goodstotal + op.getTotal();

                    op.setProductShareCommision(new BigDecimal(0));
                    if (shareMid != null && shareMid != 0L) {
                        Member shareMember = memberService.getByKey(shareMid);
                        op.setProductShareMemberId(shareMember.getId()); //设置商品分享用户id
                        //商品分享佣金
                        //op.setProductShareCommision(calcProductShareCommission(op.getProductprice(), centreId));
                    }

                    Map<String, String> map = new HashMap();
                    long sale = localRedis.increamNum(CACHE_KEY_GIFT_PACKS.concat(String.valueOf(activity.getId())), 1);
                    if (activity.getStock() < sale) {
                        localRedis.increamNum(CACHE_KEY_GIFT_PACKS.concat(String.valueOf(activity.getId())), -1);
                        throw new BDException(activity.getActivityName().concat("已卖完,请删除该商品"));
                    }
                    map.put("CACHE_KEY_GIFT_PACKS", CACHE_KEY_GIFT_PACKS.concat(String.valueOf(activity.getId())));
                    map.put("CACHE_KEY_GIFT_PACKS_TOTAL", "1");
                    list.add(map);
                } else {
                    Activity activity = activityMapper.selectByPrimaryKey(mc.getProductId());
                    op.setCartId(mc.getId());
                    op.setMid(member.getId());
                    op.setOpenid(member.getOpenid());
                    op.setSname(sname);
                    op.setMobile(mobile);
                    op.setNickname(member.getNickname());
                    op.setProductId(activity.getId());
                    op.setIsLiansuo(activity.getTeamId() == null ? 0 : 1);
                    op.setSelProductId(activity.getId());
                    op.setTotal(mc.getTotal());
                    op.setThumb(activity.getThumb());
                    op.setMarketprice(activity.getActivityPrice());
                    op.setCostprice(activity.getActivityPrice());
                    op.setProductprice(activity.getActivityPrice());
                    op.setShortTitle(activity.getActivityName());
                    op.setProductName(activity.getActivityName());
                    op.setCredit(0);
                    op.setIscredits(0);
                    op.setIsKuaidi(mc.getIsKuaidi());
                    ops.add(op);

                    goodsPrice = goodsPrice.add(activity.getActivityPrice());
                    goodstotal = goodstotal + op.getTotal();
                }
            }
            order.setHeadcommission(headcommission);
            order.setOrdersn(orderSn);
            BigDecimal discountPrice = null;
            if (couponId != null) {
                //计算优惠券金额
                discountPrice = this.calcTicketAmount(couponId, goodsPrice, centreId, productCentreList, cateringType, skuMap, BigDecimal.ZERO);
                order.setDiscountprice(discountPrice);
                order.setTrId(discountPrice == null ? null : couponId);
                couponId = null;
            }

            order.setPayIntegral(allIntegral);
            //商品总价
            order.setGoodsprice(goodsPrice);
            //订单总价
            orderPrice = goodsPrice;
            //增加包装费用
            order.setOrderprice(orderPrice);
            //支付金额
            payPrice = orderPrice.subtract(order.getDiscountprice() == null ? BigDecimal.ZERO : order.getDiscountprice());
            if (payPrice.compareTo(BigDecimal.ZERO) <= 0) {
                payPrice = BigDecimal.ZERO;
            }

            order.setPayprice(payPrice);
            if (referralsMenber != null) {
                order.setReferrals(referralsMenber.getId() == null ? 0 : referralsMenber.getId());
            }
            order.setCentreId(centre.getCentreId());
            order.setGoodstotal(goodstotal);
            //用户信息
            order.setMid(member.getId());
            order.setOpenid(member.getOpenid());
            order.setNickname(member.getNickname());
            order.setAvatar(member.getAvatar());
            order.setRealname(member.getRealname());
            if (deliveryAddress != null) {//收货地址
                order.setProvince(deliveryAddress.getProvince());
                order.setCity(deliveryAddress.getCity());
                order.setDistrict(deliveryAddress.getArea());
                order.setAddress(deliveryAddress.getAddress() + deliveryAddress.getHouseNum());
                order.setSaddress(order.getCity() + order.getDistrict() + order.getAddress());
                order.setSname(deliveryAddress.getName());
                order.setMobile(deliveryAddress.getMobile());
            } else {
                order.setSname(sname);
                order.setMobile(mobile);
            }
            order.setOutTradeNo(payNo);
            order.setPayMerchantNo(order.getOutTradeNo());
            if (null != teamLeader) {
                order.settXiaoqu(teamLeader.gettXiaoqu());
                order.settMid(teamLeader.getId());
                order.settNickname(teamLeader.getNickname());
                order.setTtMid(teamLeader.getUpTeamid());
                order.setTtNickname(teamLeader.getUpTeamname());
            }
            order.setRemark(houseNo);
            order.setIscomment(iscomment);
            //拼团订单
            if (isSpellgroup != null && isSpellgroup == 1) {
                //发起人
                order.setPromoter(promoter);
                //拼团状态 拼团中
                order.setSpellgroupStu(1);
                //带发起人订单id
                if (orderId != null) {
                    //发起人拼团订单id
                    order.setSgorderId(orderId);
                }
            }
            order.setOrderType(orderType);

            order.setShareMid(shareMid);
            order.setPortType(portType);
            if (plateType != null) {
                order.setPlateType(plateType);
            }
            int r = orderMapper.insertSelective(order);
            if (r < 0) {
                throw new BDException(BusinessCode.CREATE_ORDER_ERROR);
            } else {
                createAutoCloseOrderTask(order.getOrdersn(), order.getId(), order.getCentreId());
            }

            if (ValidateUtil.isNotEmptyCollection(usableTeamMiddleList)) {
                usableTeamMiddleList.forEach(item -> {
                    item.setOrderId(order.getId());
                });
                usableTeamMiddleMapper.insertList(usableTeamMiddleList);
            }

            resOrderId = order.getId().toString();

            for (OrderProduct op : ops) {
                op.setOrderid(order.getId());
            }
            int i = orderProductMapper.insertSelectiveBatch(ops);
            if (i < 0) {
                throw new BDException(BusinessCode.CREATE_ORDER_ERROR);
            }

            if (order.getTrId() != null) {
                TicketRecord tr = new TicketRecord();
                tr.setId(order.getTrId());
                tr.setUseTime(new Date());
                tr.setOrderId(order.getId());
                tr.setCountUsed(tr.getCountUsed() + 1);
                if (tr.getCountUsed() >= tr.getCount()) {
                    tr.setStatus(TicketStatus.USED.getStatus());
                }
                tr.setDeductAmount(order.getDiscountprice());
                ticketService.updateRecord(tr);

                ticketService.addRecordUseInfo(tr, 1, order.getId(), "订单提交，使用优惠券",new TicketRecordUse());
            }

            PlatformConfig config1 = configService.getConfigByKey(ConfigKey.TRADE_CONFIG.name(), null);
            JSONObject configValue = JSONObject.parseObject(config1.getConfigValue());
            String string = configValue.getString("RocketMQ");
            Object object = null;
            if (StringUtils.isNotBlank(string)) {
                JSONObject parseObject = JSON.parseObject(string);
                object = parseObject.get("R_ORDER");
            }
            if (object != null && "1".equals(object.toString())) {
                OrderMQProducer.sendAsync(JSON.toJSONString(ops), "ORDER_TOPIC", "CANCEL_ORDER", order.getId().toString());
            } else {
                orderMq(ops, order.getId());
            }
        }
        logger.info("---结束普通订单新增---+订单编号：" + resOrderId);
        return resOrderId;
    }
	@Override
	public Order getTeamOrder(Long mid) {
		return orderMapper.getTeamOrder(mid);
	}


}